簡體   English   中英

父進程根據退出狀態監控和派生新的子進程

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

我創建了以下代碼:

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

這個想法是一個父進程分叉 N 個子進程,每個子進程都以隨機值退出。 我希望我的父進程監視所有子進程並在退出狀態為例如 <4 時派生一個新的子進程。 這將一直持續到所有進程以 >= 4 的狀態退出。

解決了創建 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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM