Hello, I am learning C, POSIX, and Unix.

I am trying to write a code that wait until the child process is done then terminate, however, I do not know what to put in the while loop.

Parent function:
 signal(SIGCHLD, handler)
 while(child process is running)
print the number of seconds

Child function:
does something for some random amount of seconds

{

The teacher advised me to use signal(SIGCHLD, handler) part. I do not complete know what it does, all i know is that it does not ignore signal from the child. How do i know the child has ended? Basically, what do i put in the "child process is running" of my while loop. It can also be something like, while child process is not exited.

Thanks in advance guys, I am not sure if i posted in the correct thread. So sorry if i got the incorrect one.

What do you want to do exactly? It sounds like your talking about functions.

void child(void);

int main(void) {
  child();  /* Call child process */

  return 0;
}

void child(void) {
  /* Random stuff */
}
Comments
No.

If you have actually fork()ed (or spawn()ed) a child process, and you just want to check whether or not it has terminated, you want the waitpid() function.

You can also use the usleep() function to cause the parent to spin its wheels for a short bit. There are more modern and/or better ways to do this, but this is short and simple...

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
...
int status;
int seconds = 0;
do {
  /* Pause for a second */
  usleep( 1000000 );
  /* Tell the user the number of elapsed seconds */
  printf( "\r%d seconds...", ++seconds );
  /* Check the child's current status */
  waitpid( (pid_t)(-1), &status, WNOHANG );
  /* Only break if it has terminated */
} while (!WIFEXITED( status ));

Hope this helps.

Thanks guys, what i really wanted is exactly what Duoas's answer gave. I was having a hard time being able to check for the child status. I wanted the child to run, however, I do not want the parent to exit and terminate the child's time is up. I will try out the code below and let you guys know how it goes.

I am very thankful for all the help guys.

This article has been dead for over six months. Start a new discussion instead.