如何在Linux下用C++创建进程
How to create a process in C++ under Linux?
我想通过调用可执行文件来创建一个进程,就像popen
所允许的那样。但我不想通过管道与它进行实际通信:我想控制它,比如在那里发送信号,或者了解进程是否正在运行,在发送SIGINT
后等待它完成,等等,就像Python中的multiprocessing
一样。像这样:
pid_t A = create_process('foo');
pid_t B = create_process('bar');
join(B); // wait for B to return
send_signal(A, SIGINT);
该怎么走?
用例,例如:
- 监视一堆进程(比如在它们崩溃时重新启动它们)
更新
我看到了答案的方向:fork()
。然后我想修改我的用例:我想创建一个类,它在构造函数中使用一个字符串,并指定如下:当一个对象被实例化时,一个(子)进程被启动(并由该类的实例控制),当析构函数被调用时,该进程得到终止信号,析构函数在进程返回时立即返回。
现在的用例:在提升状态图中,当进入状态时启动进程,当离开状态时发送终止。我想,http://www.highscore.de/boost/process/process/tutorials.html#process.tutorials.start_child是最接近我想要的东西,除了它似乎过时了。
这不是一种非侵入性的方式吗?也许我有一个根本的误解,有更好的方法来做这类工作,如果是这样的话,我很乐意得到一些提示。
更新2
多亏了下面的答案,我想我有点明白了。我想,这个例子会打印"this is main"三次,一次用于"parent",另一次用于每个fork()
,但这是错误的。所以:谢谢你耐心的回答!
#include <iostream>
#include <string>
#include <unistd.h>
struct myclass
{
pid_t the_pid;
myclass(std::string the_call)
{
the_pid = fork();
if(the_pid == 0)
{
execl(the_call.c_str(), NULL);
}
}
};
int main( int argc, char** argv )
{
std::cout << "This is main" << std::endl;
myclass("trivial_process");
myclass("trivial_process");
}
下面的代码根本不现实,但它给了您一些想法。
pid_t pid = fork()
if (pid == 0) {
// this is child process
execl("foo", "foo", NULL);
}
// continue your code in the main process.
使用之前发布的代码,尝试以下操作:
#include <signal.h>
#include <unistd.h>
class MyProc
{
public:
MyProc( const std::string& cmd)
{
m_pid = fork()
if (pid == 0) {
execl(cmd.c_str(), cmd.c_str(), NULL);
}
}
~MyProc()
{
// Just for the case, we have 0, we do not want to kill ourself
if( m_pid > 0 )
{
kill(m_pid, SIGKILL);
wait(m_pid);
}
}
private:
pid_t m_pid;
}
我在这个例子中看到的缺点是,你不能确定,如果信号发出,这个过程已经完成(可能他不会),因为操作系统会在终止后立即继续,而另一个过程可能会延迟。为了确保这一点,您可以使用ps。。。如果对pid进行grep,那么这应该会起作用。
编辑:我添加了等待,它出现在上面的评论中!
查看fork()
(man 2 fork
)
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 使用std::multimap迭代器创建std::list
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 使用CMake创建QML插件
- 如何在c++中为模板函数实例创建快捷方式
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- OpenCV EqualizeHist()从彩色图像创建黑白图像
- 试图在visual studio上用C++创建一个桌面应用程序
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 如何在C++20中创建模板别名的推导指南
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 如何创建一个空的全局类并在启动时实例化它
- 无法创建抽象类的实例
- 链接到自行创建的dll失败
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何在C++类内存结构中创建"spacer"?
- 终端不会为C++文件创建.exe文件吗
- 在createdialog创建的窗口中捕获用于编辑控件的OnMouseMove消息