Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C-等待一个孩子终止_C_Fork_Waitpid - Fatal编程技术网

C-等待一个孩子终止

C-等待一个孩子终止,c,fork,waitpid,C,Fork,Waitpid,我正在一个循环中创建多个子进程。 每个孩子都会做自己想做的事,他们中的任何人都可以先结束。 (不确定是否相关,但:每个孩子都有一个孙子) 当一个子进程完成时,如何等待任何子进程终止并停止其他子进程 for(i=0; i<numberOfChildren; i++) { pid = fork(); if(pid < 0) { fprintf(stderr, "Error: fork Failed\n"); return EXIT_

我正在一个循环中创建多个子进程。 每个孩子都会做自己想做的事,他们中的任何人都可以先结束。 (不确定是否相关,但:每个孩子都有一个孙子)

当一个子进程完成时,如何等待任何子进程终止并停止其他子进程

for(i=0; i<numberOfChildren; i++)
{
    pid = fork();
    if(pid < 0)
    {
        fprintf(stderr, "Error: fork Failed\n");
        return EXIT_FAILURE;
    }
    /* Child Process */
    if(pid == 0)
    {
        /* Do your thing */
    }
    /* Parent process */
    else
    {
        childrenPid[i]=pid;
    }
}

for(i=0;i您可以挂起父级,直到其一个子级通过
wait
调用终止,然后
kill
其余子级:

#include <sys/types.h>
#include <wait.h>

int status;
childpid = wait(&status)
#include <sys/types.h>
#include <signal.h>

for(i = 0; i < nchildren; i++)
    if (children[i] != childpid)
        kill(children[i],SIGKILL)
#包括
#包括
智力状态;
childpid=等待(&status)
然后,如果已存储在数组中创建的所有子进程的进程ID,则可以杀死其余子进程:

#include <sys/types.h>
#include <wait.h>

int status;
childpid = wait(&status)
#include <sys/types.h>
#include <signal.h>

for(i = 0; i < nchildren; i++)
    if (children[i] != childpid)
        kill(children[i],SIGKILL)
#包括
#包括
对于(i=0;i

其中,
nchildren
是所创建子进程数的整数计数,
children
是所创建子进程的pid\t数组。

当父进程循环查看哪些子进程已退出时,执行非阻塞waitpid()使用WNOHANG,然后查看返回值,查看给定的子项是否已退出——我更喜欢这样,等待子项干净地退出。