Michał Ziobro Michał Ziobro - 1 year ago 69
C Question

Open/run another program from C and then close this program

How to execute/open/run another program from C, and not block on this but let it run simultaneously. Then I want to to do some test like server/client and then 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 any more.

Answer Source

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){
   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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download