开发者

using fork to do something while the child is running

开发者 https://www.devze.com 2023-03-30 07:45 出处:网络
So basically what i need is: pid = fork(); if (pid == -1) exit(1); if (pid == 0) { // do stuff in child } else

So basically what i need is:

pid = fork();
if (pid == -1)
   exit(1);

if (pid == 0)
{
   // do stuff in child
}
else
{
   // ONLY do stuff while child is running
}

would I need to create a tmp file right before the child exits saying that it is no longer running so the parent knows the child has exited when that file exists, or is there a simpler way to do th开发者_开发知识库is?


You can use waitpid to know if a child process is still running:

int status;
if (waitpid(pid, &status, WNOHANG) == 0) {
    // still running
}

With WNOHANG, waitpid returns immediately so that the program can do something else.

When you have nothing to do other than waiting for the child process to terminate, call waitpid without WNOHANG.


The standard way to know that the child has terminated (and get its exit code) is to use the waitpid() system call.


Check wait () and waitpid () : http://linux.die.net/man/2/wait

Here is some more resource: http://users.actcom.co.il/~choo/lupg/tutorials/multi-process/multi-process.html#child_death_wait_syscall


There's a bunch of ways to do it. If you don't need to do anything with the child output, you can set a SIGCHLD handler to reap the child when it exits, and then forget about it in your main thread of execution. You can use the SIGCHLD handler to flag the exit of the child process via an IPC mechanism.

Or you can add a while loop that checks waitpid in your else clause. You would be doing discrete units of work between polls of the child state and you wouldn't get interrupted immediately on child exit.


Use the system wait() call if you just need to check if the child has stopped running.

int pid;
int status;
while (true)
{
  pid = wait(&status);
  if (pid < 0)
    //keep waiting
  else if (pid == 0)
    //child is done
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号