Michał Ziobro Michał Ziobro - 3 months ago 8
C Question

Open/Run another program from C and than Close this program

How to execute/open/run another program from C, and not block on this but let it run simultaneously. Than I want to to do some test like. server/client and than if this has been done I want to just kill/close this program. I have read about

system() or execv()


But first seems to be blocking an waiting for results, second seems to work only on Linux? In the best case scenario I would like to have cross-platform or minimum macOS/Windows/Linux(Ubuntu) working solution. I also need to shutdown this previously opened program when I don't need it anymore.

Answer

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 + execv* 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 (pid == 0 ){
   //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(3) the process (=ask it to terminate):

 kill(pid, SIGTERM);  //please terminate 

and you can use waitpid(3) to retrieve its exit status after it has terminated .

( system(3) 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).


All in all, process management and inter-process communication (IPC) is a large topic and you might want to read up on it a little bit. The manpages are a good resource.

Comments