我希望实现类似于 CreateProcess 的功能但在 Linux 上。我做了很多研究并找到了 "Fork off and die"使用双叉在 init 下运行子进程的方法。即,让子级独立于父级运行。
因为父进程需要返回有关新创建的子进程的信息(即 pid、名称等),所以我需要知道我的代码是否遇到了竞争条件。目前,我通过管道 fork 并检索第二个 fork 的 pid,然后等待第一个 fork 退出。
int child = 0;
int fd[2] = { 0, 0 };
if (pipe (fd) != 0)
return Process();
int pid = fork();
if (pid < 0)
return Process();
if (pid == 0) // Child
{
if (setsid() != -1)
{
child = fork();
if (child == 0)
{
umask (0); // Reset umask
close (0); // Close stdin
close (1); // Close stdout
close (2); // Close stderr
execvp ( ... );
_exit (0);
}
// Do I need waitpid (child) here?
}
// Write the child PID using the pipe
write (fd[1], &child, sizeof (child));
_exit (0);
}
else // Parent
{
// Read the child PID using the pipe
read (fd[0], &child, sizeof (child));
// Remove zombie process
waitpid (pid, nullptr, 0);
// Child must finish exec by this point
return Process (child);
// Also gets name
}
问题:
- 我是否需要第二个 waitpid 来等待子进程完成 exec?
- waitpid 是否在调用 exec 时返回?
- 即使在 waitpid 之前调用了 exit 或 exec,waitpid 是否返回?
最佳答案
您不需要对第二个 child waitpid()
。当一个进程的父进程死亡时,子进程将被init
进程收养,因此不会有僵尸进程。
waitpid()
仅在它等待的子进程退出后返回。在 child 中调用 execvp()
意味着服务员会一直等到被执行的程序结束,因为那是 child 会死的时候。
waitpid()
会得到进程的退出状态。进程实际退出的时间并不重要。
关于c++ - Linux创建独立进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30200126/