Search code examples
linuxunixexecforksigchld

execl()-ing in parent process: SIGCHLD caught by ps


I'm doing an assignment on fork(),exec() and related UNIX calls where I need to show the zombie state of a (child) process. Here's the relevant piece of code:

pid = vfork();  //used vfork() for showing z state
if(pid>0)
  {
    (some sorting code)
    execl("/bin/ps","/bin/ps","a",(char*)0);             
  }

What I expect is:

(child's output)
(parent's output)
(Output of the ps command where I then would be able to show a 'defunct' entry)

What I get is:

(child's output)
(parent's output) 
No ps command output. Instead I get: Signal 17 (CHLD) caught by ps (procps version 3.2.8)

However, when sleep(int time) (some integer time in seconds) is inserted before the execl call, I get the desired output and no Signal errors are reported.

What's happening here? Does ps becomes the new parent of the (as yet-zombie) child? And why does the ps command not execute? What does sleep() do that makes ps to execute as required?

I'm new to POSIX/Linux programing so any relevance of this SIGCHLD signal with respect to my particular situation would be appreciated. Thanks!


Solution

  • I might be wrong, but I think what's happening is this:

    • Your child starts and does the sorting code while the parent blocks.
    • The child exits.
    • The parent does it's half of the if, executing ps.
    • After ps is started, SIGCHLD is sent to the parent process because of the termination of the child (signals can be slow and unpredictable)
    • If you add the sleep, SIGCHLD is delivered to the parent, who ignores it, and then control passes to ps.