I am writing a program that needs to fire another program for a number of seconds, then close it.
Feedback from the program's console would be useful, if possible.
I imagine I would close the program by retrieving the pid from the child process and running a pkill?
What would be the best way to go about this?
Thanks in advance
EDIT BY OP
void mountAd(char* adFilePath){
char* mountPoint = getNextAvailableMount();
// Set Playlist ready to be played
editPlaylist(mountPoint, adFilePath);
// Fork process and fire up ezstream
int pid = fork();
if(pid == 0){
puts ("Child Process Here\n");
execl ("/usr/local/bin/ezstream","/usr/local/bin/ezstream", "-c", "/home/hearme/radio/_test_adverts/advert01.xml", NULL);
perror("execl");
} else {
puts ("Parent Process Here\n");
}
// Advised sleep for 3 seconds until ezstream has started
sleep(3);
// More stuff to do here later
kill(pid, SIGTERM);
waitpid(pid, NULL, 0);
}
Something like this should work:
pid = fork();
if (pid < 0)
/* fork failed, error handling here */
if (pid == 0) {
/* we are the child, exec process */
execl(...);
/* this is only reached if execl fails */
perror("execl");
/* do not use exit() here, do not return from main() */
_Exit(EXIT_FAILURE);
}
/* we are the parent */
sleep(duration);
kill(pid, SIGKILL);
/* use wait/waitpid/waitid as needed */
waitpid(pid, NULL, 0);
Notice that this does not correctly perform error checking for the case when the program you want to run cannot be found or executed, a more elaborate scheme is needed for that case, if you are interested I could elaborate.