gpt4 book ai didi

c - 子进程退出后如何执行父进程?

转载 作者:行者123 更新时间:2023-12-02 06:13:27 25 4
gpt4 key购买 nike

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main (int argc, char *argv[]) {
pid_t childpid = 0;
int i, n;

if (argc != 2){
fprintf(stderr, "Usage: %s processes\n", argv[0]);
return 1;
}
n = atoi(argv[1]);
for (i = 1; i < n; i++)
if (childpid = fork())
break;

if (childpid>0){ // parent process
while (i>1) {
wait(NULL);
i--;
}
}

fprintf(stderr, "i:%d process ID:%ld parent ID:%ld child ID:%ld\n",
i, (long)getpid(), (long)getppid(), (long)childpid);
return 0;
}

在此代码中,我如何在所有子进程退出后打印进程信息(父进程)。

输出:

i:1  process ID:2313  parent ID:2307  child ID:2314
i:3 process ID:2315 parent ID:2314 child ID:0
i:1 process ID:2314 parent ID:1 child ID:2315

我需要子进程先退出,然后父进程需要打印它的进程信息。

最佳答案

使等待跟踪循环提供更多信息和更彻底。特别是,在循环的第一个循环中,父进程有 n == 1,因此它从不等待。最好是反复等待,直到没有更多的 child 可以等待。

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

int main(int argc, char *argv[])
{
pid_t childpid = 0;
int i, n;

if (argc != 2)
{
fprintf(stderr, "Usage: %s processes\n", argv[0]);
return 1;
}
n = atoi(argv[1]);
printf("Creating %d sub-processes\n", n);
fflush(stdout);
for (i = 1; i < n; i++)
{
if ((childpid = fork()) != 0)
break;
}

printf("%d: i = %d, childpid = %d\n", (int)getpid(), i, childpid);

if (childpid != 0)
{
int corpse;
int status;
while ((corpse = wait(&status)) > 0)
printf("%d: child %d exited with status 0x%.4X\n", (int)getpid(), corpse, status);
}

printf("i: %d process ID: %5ld parent ID: %5ld child ID: %5ld\n",
i, (long)getpid(), (long)getppid(), (long)childpid);
return 0;
}

示例输出(编译为 fork73 的程序):

$ fork73 4
Creating 4 sub-processes
62621: i = 1, childpid = 62622
62622: i = 2, childpid = 62623
62623: i = 3, childpid = 62624
62624: i = 4, childpid = 0
i: 4 process ID: 62624 parent ID: 62623 child ID: 0
62623: child 62624 exited with status 0x0000
i: 3 process ID: 62623 parent ID: 62622 child ID: 62624
62622: child 62623 exited with status 0x0000
i: 2 process ID: 62622 parent ID: 62621 child ID: 62623
62621: child 62622 exited with status 0x0000
i: 1 process ID: 62621 parent ID: 877 child ID: 62622
$

关于c - 子进程退出后如何执行父进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46757143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com