检查子进程是否在C中终止

问题描述 投票:0回答:1

waitpid(-1, NULL, 0) 停止调用进程,直到它的一个子进程改变状态(所以不一定终止)。我想在调用后检查 waitpid(-1, NULL, 0),是否有特定的孩子终止,我是通过使用 waitpid(<child_pid>, NULL, WNOHANG)和faik与 WNOHANG 作为一个选项,在执行过程中使用 <child_pid> 不会被打断,它应该会回到 0 如果它是活动的,否则 <child_pid>-1 如果发生错误。

但我的程序返回 -1,而不是某个值 >= 0 正如预期的那样。

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

int main(){

        pid_t pid = fork();
        if(pid == 0){ 
                pid_t child_pid = getpid();
                printf("Child %d starts\n", child_pid); 
                sleep(5);
                printf("Child %d exits\n", child_pid);
                return 0;
        }   
        // parent waits for child status change
        waitpid(-1, NULL, 0); 
        printf("Parent waited\n");
        // parents checks status
        pid_t status = waitpid(pid, NULL, WNOHANG);
        printf("%d status is %d\n", pid, status);

        return 0;
}

输出:等待pid(-1, NULL, 0)停止调用进程,直到他的一个子进程改变状态。

Child 7823 starts
Child 7823 exits
Parent waited
7823 status is -1
c process fork parent-child waitpid
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.