简体   繁体   中英

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. I want my parent process to monitor all the child processes and fork a new child if the exit status is, for instance <4. This will be going on until all process exit with a status >= 4.

Solved creating a function copying the code from parent and child (keeping the code in main() untouched). 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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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