Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using fork(), how can I make child process run always first?

Child and parent process execution is parallel and which starts first depends on OS scheduling. But what can be done to start child always before the parent?

This is the pseudo code for my problem,

int start_test()
{
   pid_t pid;
   pid = fork();
   if(pid == 0) {
      execv("XXX", XXX);
   } else if(pid > 0) {
     pid = fork();
    if(pid == 0) {
       execv("XXX", XXX);
    } else {
       // Do something
    }
   }
  return 0;
}
int main()
{
   start_test();
   return 0;
}

I wants to make first execv execute first than parent creates new process again. Every execv should be in sequence.

like image 489
Jagdish Avatar asked Feb 11 '23 03:02

Jagdish


1 Answers

I don't really know why people keep telling not to rely on this behaviour, it's actually used a lot in tracing programs (strace, ldtrace, ...).

First, fork your process and get the child pid, stop the child, and resume it in the parent:

pid_t pid = fork();
if (pid == -1)
    abort();
else if (pid == 0) {
    raise(SIGSTOP); // stop the child
} else {
    waitpid(pid, NULL, WUNTRACED); // wait until the child is stopped
    kill(pid, SIGCONT); // resume the child
}
like image 81
Snaipe Avatar answered Feb 13 '23 03:02

Snaipe