简体   繁体   中英

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". But I tried the WNOHANG, but the somehow my second checking is not working/or i can't stop the child process. 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. Checking man 2 wait and reading what the argument of pid stands for

The pid parameter specifies the set of child processes for which to wait. If pid is -1, the call waits for any child process. If pid is greater than zero, the call waits for the process with process id pid. If pid is less than -1, the call waits for any process whose process group id equals the absolute value of 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.

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. If the child process has finished then it will return the pid of the child.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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