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(...);
}
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With