Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running two programs concurrently

I have two C++ programs built in Ubuntu, and I want to run them concurrently. I do not want to combine them into one C++ project and run each on a different thread, as this is causing me all sorts of problems.

The solution I effectively want to emulate, is when I open two tabs in the terminal, and run each program in a separate tab. However, I also want one program (let's call this Program A) to be able to quit and rerun the other program (Program B). This cannot be achieved just in the terminal.

So what I want to do is to write some C++ code in Program A, which can run and quit Program B at any point. Both programs must run concurrently, so that Program A doesn't have to wait until Program B returns before continuing on with Program A.

Any ideas? Thanks!

like image 554
Karnivaurus Avatar asked Dec 24 '22 15:12

Karnivaurus


2 Answers

In Linux you can fork the current process, which creates a new process. Then you have to launch the new process with some exec system call.

Refer to: http://man7.org/linux/man-pages/man2/execve.2.html

For example:

#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);
    }
}
like image 182
dau_sama Avatar answered Dec 27 '22 05:12

dau_sama


You have multiple options here:

  1. The traditional POSIX fork / exec (there are literally tons of examples on how to do this in SO, for example this one).
  2. If you can use Boost then Boost process is an option.
  3. If you can use Qt then QProcess is an option.

Boost and Qt also provide nice means manipulating the standard input/output of the child process if this is important. If not the classical POSIX means should do fine.

like image 44
Rudolfs Bundulis Avatar answered Dec 27 '22 03:12

Rudolfs Bundulis