如何在Linux下用C++创建进程

How to create a process in C++ under Linux?

本文关键字:C++ 创建 进程 下用 Linux      更新时间:2023-10-16

我想通过调用可执行文件来创建一个进程,就像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