1

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Michał Ziobro
  • 10,759
  • 11
  • 88
  • 143

2 Answers2

3

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.

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
  • thx this helps a lot :) I think I will use it in the future but now I redesign my test to be simpler: 1. run test server on separate pthread 2. do shell cmd to echo this server with popen() 3. get cmd output and assert it is correct. – Michał Ziobro Aug 13 '16 at 14:13
0

How to execute/open/run another program from C ?:

use system

How not to block on it?

you have to implement multitasking, so use fork to create another processes or pthread_create to create another thread, take a look at this

I would like to have cross-platform or minimum macOS/Windows/Linux(Ubuntu) working solution.

system works on linux and windows but i don't have any ideas about the other platforms

Community
  • 1
  • 1
Mouin
  • 1,025
  • 4
  • 19
  • 33