Gary
Gary

Reputation: 916

Working with processes in C

just a quick question regarding C and processes. In my program, I create another child process and use a two-directional pipe to communicate between the child and parent. The child calls execl() to run yet another program.

My question is: I want the parent to wait n amount of seconds and then check if the program that the child has run has exited (and with what status). Something like waitpid() but if the child doesn't exit in n seconds, I'd like to do something different.

Upvotes: 1

Views: 277

Answers (2)

nos
nos

Reputation: 229342

You can use an alarm to interrupt waitpid() after N seconds (don't use this approach in a multithreaded environment though)

   signal(SIGALRM,my_dummy_handler);
   alarm(10);

   pid_t p = waitpid(...);
   if(p == -1) {
     if(errno == EINTR) {
        //timeout occured
      } else {
        //handle other error
     }

Upvotes: 1

Bastien Léonard
Bastien Léonard

Reputation: 61823

You can use waitpid() with WNOHANG as option to poll, or register a signal handler for SIGCHLD.

Upvotes: 2

Related Questions