Yas*_*oor 1 c++ multithreading fork pthreads system-calls
我编写了一个程序,在主程序中创建一个线程,并用于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;
}
Run Code Online (Sandbox Code Playgroud)
我的建议是:不要做你正在做的事。如果您想创建一个独立运行的子进程,请研究fork和exec家庭函数。这就是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';
}
Run Code Online (Sandbox Code Playgroud)
使用的确切变体exec取决于command。如果它是可执行程序的有效路径(绝对或相对),则execl效果很好。如果它是 then 中的“命令”,PATH则使用execlp.
| 归档时间: |
|
| 查看次数: |
7600 次 |
| 最近记录: |