简体   繁体   中英

waitPID function not checking if the child process exited

I am unable to get the waitPid to tell me if the child process exited or not. In the parent process this is what I am doing:

if (forkID != 0) {
    
        pid_t result = waitpid(forkID, &status, WNOHANG);
        if (result == 0) {
          // Child still alive
            std::cout<<"Child Alive"<<std::endl;
        } else if (result == -1) {
          // Error
            std::cout<<"Error"<<std::endl;
        } else {
          // Child exited
            std::cout<<"Child Exited"<<std::endl;
        }

        DriverParser P;
        while (!std::cin.eof()) {

             std::string line;
             std::getline(std::cin, line);

              arguments = P.BeginParsing(line);
              if (arguments.size() > 0) {
                  for (int k = 0; k < 4; k++) {
                      finalArguments[k] = arguments[k];
                  }
                  
                  close(fd[0]);
                  write(fd[1],finalArguments,4*sizeof(int));
                  close(fd[1]);
                  
                  
                  
              }
         }
        
        
       // pid = wait(&status);
        
      //  std::cout<<waitpid(forkID, &status, 0)<<std::endl;
    

}else if (forkID == 0) {
   // child: reading only, so close the write-descriptor
    
    std::cout<<"I am child process my PID is: "<<getpid()<<std::endl;

    execv("./a.out", argList);
    
    // close the read-descriptor
    close(fd[0]);
    
   
    
}

I am basically sending the result of the parser as it reads from the stdin via pipe to child process, and then executing a process in execv. Now when this program exits using exit(0) - I am not seeing Child Exited on the terminal which means the waitpid is essentially not working for me.

What should I do?

You are calling waitpid with WNOHANG :

pid_t result = waitpid(forkID, &status, WNOHANG);

I shared with you the documentation , which says:

If WNOHANG was specified in options and there were no children in a waitable state, then waitid() returns 0 immediately and the state of the siginfo_t structure pointed to by infop is unspecified. To distinguish this case from that where a child was in a waitable state, zero out the si_pid field before the call and check for a nonzero value in this field after the call returns.

It also says:

WNOHANG
return immediately if no child has exited.

Considering that the call to waitpid happens immediately after fork, the chances are that the child is still running.

If you want to wait for the child process to end, just remove the WNOHANG option (pass 0 instead):

pid_t result = waitpid(forkID, &status, 0);

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