同时运行两个程序

4
我在Ubuntu中有两个C++程序,我想要并行运行它们。我不想将它们合并成一个C++项目并在不同的线程上运行每个程序,因为这会导致各种问题。
实际上,我想要模拟的解决方案是,在终端中打开两个选项卡,并在不同的选项卡中运行每个程序。但是,我还希望其中一个程序(让我们称其为程序A)能够退出并重新运行另一个程序(程序B)。这不能仅在终端中实现。
因此,我想要做的是在程序A中编写一些C++代码,以便可以在任何时候运行并退出程序B。两个程序必须同时运行,以便程序A在程序B返回之前不必等待才能继续执行程序A。
有什么想法吗?谢谢!
3个回答

4
在Linux中,您可以使用fork命令创建一个新进程。然后,您需要使用一些exec系统调用来启动新的进程。
参考: http://man7.org/linux/man-pages/man2/execve.2.html 例如:
#include <unistd.h> /* for fork */
#include <sys/types.h> /* for pid_t */
#include <sys/wait.h> /* for wait */

int main(int argc,char** argv)
{
    pid_t pid=fork();
    if (pid==0)
    {
      execv("/bin/echo",argv);
    }
}

3
请看Linux操作系统调用中的fork()exec()fork()调用将创建当前进程的两个副本,它们继续同时执行。
  • 在父进程中,fork()的返回值是子进程的PID(进程ID)。
  • 在子进程中,fork()的返回值为0。
  • 出现错误时,fork()的返回值为-1。
您可以利用这一点来控制父进程和子进程的行为。 举个例子:
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>

int main(int argc,char** argv)
{
    char* progB = "/bin/progB";
    char* args[progName, "arg1", "arg2", ..., NULL];
    char* env[NULL]; // can fill in environment here.

    pid_t pid=fork();
    if (pid==0)
    {
        // In child...
        execv(progB, args, env);
    }
    else if (pid == -1) 
    {
        // handle error...
    } 
    else 
    {
        // In parent; pid is the child process.
        // can wait for child or kill child here.
    }
}

如果您想等待子进程退出(上述第三种情况),您可以使用wait(2), 在成功终止时返回子进程pid,错误时返回-1:

pid_t result = waitpid(pid, &status, options);

为了在事先终止进程,您可以按照 kill(2) 中描述的方法发送一个 kill 信号:
int result = kill(pid, SIGKILL); // or whatever signal you wish

这将使您能够按照原始问题中的描述管理进程。

3
您有多个选择:
  1. 传统的POSIX fork / exec (在SO上有大量示例,例如这个)。
  2. 如果可以使用Boost,则可以使用Boost process
  3. 如果可以使用Qt,则可以使用QProcess

如果需要,Boost和Qt还提供了很好的手段来操作子进程的标准输入/输出。 如果不需要,则经典的POSIX手段应该足够。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接