c - 单父进程的多个子进程

标签 c linux terminal

如何在此处使用 waitpid() 命令来等待其子级的终止,然后显示 PID。

for(int i=0; i < 5 ;i++)
{
    if(pid > 0)
    {
        pid = fork();
        c++;

        if(pid==0)
        {
            printf("child: %d \n",c);
            printf("child process with pid self %d \n", getpid());              


         }

    }
}

最佳答案

你应该像这样重构你的循环:

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <errno.h>
...
pid_t pid;

for (int i = 0; i < 5; i++) {
    pid = fork();

    if (pid == 0) {
        printf("child process with pid %d\n", getpid());
        ...
        exit(0);
    } else if (pid > 0) {
        /* the child has been forked and we are in the parent */
    } else {
        /* could not fork child */
    }
}

int status;

while ((pid = waitpid(-1, &status, 0))) {
    if (pid == -1 && errno == ECHILD) {
        break;
    } else if (pid == -1) {
        perror("waitpid");
    } else if (WIFEXITED(status)) {
        printf("%d exited, status=%d\n", pid, WEXITSTATUS(status));
    } else if (WIFSIGNALED(status)) {
        printf("%d killed by signal %d\n", pid, WTERMSIG(status));
    } else if (WIFSTOPPED(status)) {
        printf("%d stopped by signal %d\n", pid, WSTOPSIG(status));
    } else if (WIFCONTINUED(status)) {
        printf("%d continued\n", pid);
    }
}

请注意在子 block 末尾包含对 exit 的调用。这是为了防止子进程继续执行循环所必需的。

第二个循环应该运行,直到所有子循环都终止。

关于c - 单父进程的多个子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42178248/

相关文章:

linux - 无法删除具有特殊字符的 Linux 中的文件夹

linux - 如何交叉编译 arm64 的 lttng-modules?

terminal - 使用 AppleScript 编辑器在终端中输入多个命令

C - 由 realloc 创建的数组的大小

c - 通过函数调用进行的静态初始化在 C 中是线程安全的吗?

c++ - Linux 上是否有等效的 .def 文件来控制共享库中导出的函数名称?

python - 无法将 Django 管理命令添加到我的开发环境中的项目

android - 如何在Android Studio终端中运行gradle命令?

macos - 打开新标签页时如何更改终端背景颜色?

c - 全局变量似乎有两个不同的地址......?