c++ - 使用 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;
}
解决方案
我的建议是:不要做你该做的。如果您想创建一个独立运行的子进程,请研究fork
和exec
家庭功能。这就是system
将使用“引擎盖下”的内容。
线程并不像进程那样真正独立。当您的“主”进程结束时,所有线程也会结束。在您的特定情况下,线程似乎继续运行,而主进程似乎由于pthread_join
调用而结束,它只会等待线程退出。如果您删除加入调用,则线程(以及您的“命令”)将被终止。
有一些方法可以分离线程,以便它们可以更独立地运行(例如,您不必加入分离的线程)但主进程仍然无法结束,而是您必须结束主线程,这将保持只要有分离的线程在运行,进程就会运行。
使用fork
andexec
实际上很简单,也不是很复杂:
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
.
推荐阅读
- c# - Enum.TryParse 在仅限于 Enum 的泛型中不被接受
- c - 如何更改字符数组中的特定字符串?
- java - 在android的SearchView项目中更改搜索图标和文本的颜色
- python - 如何在 Python 中使用 pyfiglet 使打印文本居中
- python - 无法使用适用于 AWS Lambda 的无服务器框架加载 Python 依赖项:错误:STDOUT
- applescript - Applescript 使下一个选项卡成为 Photoshop 中的当前文档
- javascript - 从 HTML 页面获取动态内容 Python
- javascript - Firebase“添加”数据到现有文档不起作用
- swiftui - UIViewControllerRepresentable 奇怪的释放
- windows - 重命名文件夹后如何使用 Perforce P4V 客户端完全删除文件夹?