简体   繁体   English

父进程根据退出状态监控和派生新的子进程

[英]Parent process to monitore and fork new child processes depending on exit status

I've created the below code:我创建了以下代码:

int main(int argc, char *argv[])
{
        int i, n, N;
        pid_t pid;
        int status;

        N = atoi(argv[1]);

        for(i = 0; i < N; i++) {
                pid = fork();
                if(pid==0) {
                        srand(getpid() * getppid());
                        n = rand() % 10 + 1;
                        printf("I'm child nº %d with childpid %d, parent pid = %d, n = %d\n", i, getpid(), getppid(), n);
                        exit(n);
                }
        }

        while ((pid = waitpid(pid, &status, 0))) {
                if (pid < 0)
                        ;
                else if (WEXITSTATUS(status) < 4)
                        printf("exit status %d lower than 4\n", WEXITSTATUS(status));
        }
        wait(NULL);
        return 0;
}

The idea is a parent process forking N child process and each of them exiting with a random value.这个想法是一个父进程分叉 N 个子进程,每个子进程都以随机值退出。 I want my parent process to monitor all the child processes and fork a new child if the exit status is, for instance <4.我希望我的父进程监视所有子进程并在退出状态为例如 <4 时派生一个新的子进程。 This will be going on until all process exit with a status >= 4.这将一直持续到所有进程以 >= 4 的状态退出。

Solved creating a function copying the code from parent and child (keeping the code in main() untouched).解决了创建 function 复制父子代码的问题(保持 main() 中的代码不变)。 The parent calls the function, the function forks another process, and the parent in the same function calls the function recursively under the conditions we choose. The parent calls the function, the function forks another process, and the parent in the same function calls the function recursively under the conditions we choose.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM