The POSIX way to do it (which maybe could be used in Windows too -- https://technet.microsoft.com/en-us/library/bb463220.aspx ?)
is to use a fork + exec* combo:
You use fork to create a new process that copies the current process.
Your handle to that process is an int process identifier (pid):
int pid;
if (0 > (pid=fork()){
perror("fork failed");
return -1;
}
if (0 == pid){
//CHILD PROCESS
printf("I'm the child process, my pid is: %d\n", getpid());
}
//pid > 0 ==> PARENT PROCESS
puts ("I'm the parent process");
printf("The pid of the child I've just spawned is %d\n", pid);
To run an executable in the child process, use an exec* function to replace the current (e.g., the child's if you run it in the child) process image with a process image loaded from an executable file.
In the parent, you can then use the pid handle to kill the process (=ask it to terminate):
kill(pid, SIGTERM); //please terminate
and you can use waitpid to retrieve its exit status after it has terminated .
( system internally uses fork
+ execv
(it execs a shell) + waitpid
. Because the waitpid
part isn't separate in system
, system
makes you wait for the child process to finish.)
You'll probably also want to look into dup2 and pipe or socketpair to set up a fildescriptor-based communication channel with the child process (there are other options such as shared memory, message queues, or signals if you only need very basic communication).
The manpages are a good resource on managing processes and IPC.