Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waitpid and fork/exec's non-blocking advantage over a syscall?

I always hear that you should never use system() and instead fork/exec because system() blocks the parent process.

If so, am I doing something wrong by calling waitpid(), which also blocks the parent process when I do a fork/exec? Is there a way around calling waitpid...I always thought it was necessary when doing a fork/exec.

pid_t pid = fork();

if (pid == -1)
{
    // failed to fork
} 
else if (pid > 0)
{
    int status;
    waitpid(pid, &status, 0);
}
else 
{
    execve(...);
}
like image 314
lolololol ol Avatar asked Oct 11 '25 19:10

lolololol ol


2 Answers

The WNOHANG flag (set in the options argument) will make the call to waitpid() non-blocking.

You'll have to call it periodically to check if the child is finished yet.

Or you could setup SIGCHLD to take care of the children.

like image 77
Attie Avatar answered Oct 14 '25 09:10

Attie


If you want to do other stuff whilst the child process is off doing it's thing, you can set up a trap for SIGCHLD that handles the child finishing/exiting. Like in this very simple example.

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

pid_t pid;
int finished=0;

void zombie_hunter(int sig)
    {
    int status;
    waitpid(pid, &status, 0);
    printf("Got status %d from child\n",status);
    finished=1;
    }

int main(void)
    {
    signal(SIGCHLD,zombie_hunter);

    pid = fork();

    if (pid == -1)
        {
        exit(1);
        } 
    else if (pid == 0)
        {
        sleep(10);
        exit(0);
        }

    while(!finished)
        {
        printf("waiting...\n");
        sleep(1);
        }
    }
like image 32
Chris Turner Avatar answered Oct 14 '25 09:10

Chris Turner