函数测试–fork

函数测试–fork

fork三个子进程,等待他们退出的状态

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

int main(void) {
    int child_ret;
    pid_t pid_fork, pid_ret;
    printf("before fork\n");
    int count = 3 ; 

next:
    if ((pid_fork = fork()) < 0) {
        // fork 出错
        printf("fork error");
    } else if (pid_fork == 0) {
        // 子进程
        printf("child : process's pid=%d,sleep 1 sec\n", getpid());
        sleep(count);
        printf("child : process's pid=%d, quit\n",getpid());
        printf("--------------------------------------------\n");
        return 10 ;
        // exit(3);
    } else {
        count -- ; 
        if(count >0 ) goto next ;
        printf("father : parent process wait child terminate...\n");
        while(1) {
            pid_ret = wait(&child_ret);   // 如果没有子进程,则返回 -1 立即返回
            printf("father : wait process's pid=%d,status=0x%X,exit value=%d(0x%X) child_ret = %d\n=========================\n\n", pid_ret, child_ret,
                       WEXITSTATUS(child_ret), WEXITSTATUS(child_ret), child_ret);
            if(pid_ret == -1) break ;
            usleep(500000) ;
        }
        printf("father : over...\n");
    }

    exit(0);
} 

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注