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

后端 未结 6 698
星月不相逢
星月不相逢 2020-12-19 20:11

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

6条回答
  •  一向
    一向 (楼主)
    2020-12-19 20:35

    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
    }
    

提交回复
热议问题