建立子进程

如下程序,建立了一个子进程,且父进程等待子进程的退出而退出:spa

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main() {
    pid_t pid;
    char *message;
    int n;
    int exit_code;
    
    printf("fork program starting\n");
    pid = fork();
    switch(pid) {
    case -1:
        perror("fork failed");
        exit(1);
    case 0:
        message = "This is the child";
        n = 5;
        exit_code = 37;
        break;
    default:
        message = "This is the parent";
        n = 3;
        exit_code = 0;
        break;
    }

    for(; n > 0; n--) {
        puts(message);
        sleep(1);
    }
    
    if(pid != 0) {
        int stat_val;
        pid_t child_pid;

        //while(1);
                //等待子进程的退出
        child_pid = wait(&stat_val);
        printf("Child has finished: PID = %d\n", child_pid);

        if(WIFEXITED(stat_val))
            printf("Child exited with code %d\n", WEXITSTATUS(stat_val));
        else
            printf("Child terminated abnormally\n");
    }
    
    exit(exit_code);
}    

运行结果:code

须要注意的是:假如上面程序中子进程退出了,可是父进程在wait()以前,子进程在进程表中的信息仍是存在的,可在wait()前面暂停,用#ps -al命令查看,结果以下:orm

此时,假如kill了父进程,那么子进程就变成了“僵尸进程”(进程已经再也不运行,但它仍存在于系统下) ,此后子进程将认init进程为父进程。由init进程接管,直到init进程发现并释放它。blog

相关文章
相关标签/搜索