创建子进程

以下程序,创建了一个子进程,且父进程等待子进程的退出而退出:

#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);
}    

运行结果:

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

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

 

posted on 2016-03-15 17:37  suwen  阅读(255)  评论(0编辑  收藏  举报

导航