使用fork(),如何使子进程始终始终运行? [英] Using fork(), how can I make child process run always first?

查看:85
本文介绍了使用fork(),如何使子进程始终始终运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

子进程和父进程的执行是并行的,首先开始取决于操作系统调度.但是如何做才能总是在父母之前就开始生孩子?

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;
}

我想让第一个execv首先执行,而不是父级再次创建新进程.每个execv应该按顺序进行.

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

推荐答案

我真的不知道为什么人们总是告诉人们不要依靠这种行为,它在跟踪程序(strace,ldtrace,...).

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, ...).

首先,派生您的进程并获取子进程pid,停止该子进程,然后在父进程中恢复它:

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
}

这篇关于使用fork(),如何使子进程始终始终运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆