c++ - Linux创建独立进程

标签 c++ linux process fork posix

我希望实现类似于 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/

相关文章:

c++ - 如何通过鼠标移动使OpenGL相机在SFML中移动

linux - Bash 忽略 $

c++ - LIBPATHS 未在 Makefile 中使用,无法找到共享对象

windows - Closehandle() 不终止进程

Linux:多核 CPU 中的进程和线程

c++ - 这是 boost::filesystem 中的错误吗?为什么 boost::filesystem::path::string() 在 Windows 和 Linux 上没有相同的签名?

c++ - 如何使用 GLFW 修复黑屏

c++ - 为什么这个子类代码会导致运行时错误?

linux - 如何防止 GCC 传入默认标志?

c - 确定 read() 和 fork() 系统调用的可能输出