首页 > 解决方案 > 使用 system() 创建独立的子进程

问题描述

我编写了一个程序,在其中我在主线程中创建一个线程并用于system()从该线程启动另一个进程。system()我也使用main 函数中的启动相同的过程。即使父进程死亡,从线程启动的进程似乎仍然活着。但是从主函数调用的函数与父函数一起死亡。任何想法为什么会发生这种情况。

请在下面找到代码结构:

void *thread_func(void *arg)
{
     system(command.c_str());        
}

int main()
{
    pthread_create(&thread_id, NULL, thread_func, NULL);
    .... 
    system(command.c_str());
    while (true)
    {
        ....
    }
    pthread_join(thread_id, NULL);
    return 0;
}

标签: c++multithreadingpthreadsforksystem-calls

解决方案


我的建议是:不要做你该做的。如果您想创建一个独立运行的子进程,请研究forkexec家庭功能。这就是system将使用“引擎盖下”的内容。

线程并不像进程那样真正独立。当您的“主”进程结束时,所有线程也会结束。在您的特定情况下,线程似乎继续运行,而主进程似乎由于pthread_join调用而结束,它只会等待线程退出。如果您删除加入调用,则线程(以及您的“命令”)将被终止。

有一些方法可以分离线程,以便它们可以更独立地运行(例如,您不必加入分离的线程)但主进程仍然无法结束,而是您必须结束主线程,这将保持只要有分离的线程在运行,进程就会运行。


使用forkandexec实际上很简单,也不是很复杂:

int pid = fork();
if (pid == 0)
{
    // We are in the child process, execute the command
    execl(command.c_str(), command.c_str(), nullptr);

    // If execl returns, there was an error
    std::cout << "Exec error: " << errno << ", " << strerror(errno) << '\n';

    // Exit child process
    exit(1);
}
else if (pid > 0)
{
    // The parent process, do whatever is needed
    // The parent process can even exit while the child process is running, since it's independent
}
else
{
    // Error forking, still in parent process (there are no child process at this point)
    std::cout << "Fork error: " << errno << ", " << strerror(errno) << '\n';
}

使用的确切变体exec取决于command. 如果它是可执行程序的有效路径(绝对或相对),则execl运行良好。如果它是“命令”,PATH则使用execlp.


推荐阅读