简体   繁体   English

检查子进程的状态

[英]Checking the status of child process

Hi am bit new to c programming.I have the following piece of code, basically the program need to check the status of the child process and parent waits until the child terminates and then prints "the child has terminated". 嗨,我是c编程的新手。我有以下代码,基本上该程序需要检查子进程的状态,父进程要等到子进程终止后再打印“子进程终止”。 But I tried the WNOHANG, but the somehow my second checking is not working/or i can't stop the child process. 但是我尝试了WNOHANG,但是以某种方式我的第二次检查不起作用/或者我无法停止子进程。 Any idea guys? 有想法吗? Thanks in advance. 提前致谢。

code: 码:

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

int main()
{
    int pid;
    int ppid;
    int status;
    pid=vfork();
    pid_t return_pid = waitpid(pid, &status, WNOHANG);

    if (pid<0) {
        printf("\n Error ");
        exit(1);
    } else if (pid==0) {
        printf("\n Hello I am the child process ");
        printf("\n My pid is %d %d ",return_pid, getpid());
        exit(0);
    } else if (return_pid == pid) {
            printf("child is finished %d %d", return_pid, pid);
            exit(0);
    } else {
        printf("\n Hello I am the parent process %d %d", return_pid, pid);
        printf("\n My actual pid is %d %d \n ",return_pid, getpid());
        exit(1);
    }
}

I wonder if maybe your waitpid is in the wrong location. 我想知道您的waitpid是否在错误的位置。 Checking man 2 wait and reading what the argument of pid stands for 检查man 2 wait并阅读pid的参数代表什么

The pid parameter specifies the set of child processes for which to wait. pid参数指定要等待的子进程集。 If pid is -1, the call waits for any child process. 如果pid为-1,则调用等待任何子进程。 If pid is 0, the call waits for any child process in the process group of the caller. 如果pid为0,则调用等待调用者的进程组中的任何子进程。 If pid is greater than zero, the call waits for the process with process id pid. 如果pid大于零,则调用等待进程ID为pid的进程。 If pid is less than -1, the call waits for any process whose process group id equals the absolute value of pid. 如果pid小于-1,则调用等待进程组ID等于pid的绝对值的任何进程。

The bold text, to me, indicates that the child could be waiting on itself? 对我来说,粗体字表示孩子可能正在等待自己吗? The value of vfork will return 0 for the child. vfork的值将为子级返回0。

Also, the WNOHANG option will cause waitpid to return immediately if the child has not exited, meaning the parent will not wait for the child to finish. 同样,如果孩子没有退出,WNOHANG选项将导致waitpid立即返回,这意味着父级不会等待孩子完成。 If the child process has finished then it will return the pid of the child. 如果子进程已完成,则它将返回子进程的pid。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM