【发布时间】:2015-07-23 20:57:30
【问题描述】:
我希望在 Linux 上实现类似于 CreateProcess 的功能。我做了很多研究,发现"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 是否会返回?
【问题讨论】:
-
为什么要双叉?当新进程不应该是原始进程的子进程时,就会执行双分叉,这与您想要做的完全相反。
-
这正是我想做的。我想创建一个与父进程无关的进程。因此,即使父母去世,孩子也会继续。我返回孩子的 PID,以便以后可以根据需要对其进行调试。这就是 CreateProcess 函数在 Windows 上的作用,我需要在 Linux 上复制它。
-
在双分叉方法中,新进程不是原始进程的子进程。你不能一边吃蛋糕一边吃,除非你以一种可怕的方式破解某些东西。
-
为什么要创建一个不是原始进程子进程的进程?
-
我知道这不是个孩子。我不希望它成为一个孩子,我希望它独立,摆脱 Init。我在这里启动一个守护进程。这个新进程就像任何其他进程一样,我将能够像任何远程进程一样“附加”到它。这是我在这里构建的一个远程过程分析库。
标签: c++ linux process fork posix