I am trying to run two pre-made executables within a new program, but run these two original executables each within their own child process, so basically, just make a parent process fork() into two childs. However, I see A LOT of questions posed regarding running multiple child processes in parallel, but I want to run one first, wait for the first to finish, and then run the second. And maybe this goes without say, but then, afterwards, return to the parent process after the second child is finished (so I can just print some message notifying a user that both executables are finished). I am very unskilled with using the wait() and waitpid() functions and these are quite critical to what I am trying to do. Anyway someone could give me a quick sample program that would ensure that one child process runs subsequent to the second? Thank you so much for your time!!
Asked
Active
Viewed 206 times
0
-
2Wait for the first one before you fork the second one. – alani Jul 11 '20 at 23:29
-
1There is an example at https://stackoverflow.com/a/19099707/13596037 - do this for the first child, and then do the whole thing again for the second child. – alani Jul 11 '20 at 23:34
1 Answers
3
system("command1");
system("command2");
This is roughly equivalent to the following:
{
const char* child_argv[] = { "command1", NULL };
pid_t pid = fork();
if (!pid) {
execvp(child_argv[0], child_argv);
exit(255); // errno should probably be sent to parent first.
}
waitpid(pid, NULL, 0);
}
{
const char* child_argv[] = { "command2", NULL };
pid_t pid = fork();
if (!pid) {
execvp(child_argv[0], child_argv);
exit(255); // errno should probably be sent to parent first.
}
waitpid(pid, NULL, 0);
}
On a POSIX system, you can use spawn
instead of fork
.
{
const char* child_argv[] = { "command1", NULL };
pid_t pid;
posix_spawnp(&pid, child_argv[0], NULL, NULL, child_argv, environ);
waitpid(pid, NULL, 0);
}
{
const char* child_argv[] = { "command2", NULL };
pid_t pid;
posix_spawnp(&pid, child_argv[0], NULL, NULL, child_argv, environ);
waitpid(pid, NULL, 0);
}
The latter two solutions avoid using a shell (which is a good thing if you have a file name or path rather than shell command).
Of course, all three snippets are lacking error checking.

ikegami
- 367,544
- 15
- 269
- 518
-
-
1Fine - apart from the fact that if the exec fails then you will have a lot more happening than you bargained for - put an exit after the exec. – alani Jul 11 '20 at 23:41
-
Since properly handling all of the corner cases is complex, and not really the point of this Q/A, how about using `posix_spawn` instead? – Jonathon Reinhart Jul 11 '20 at 23:55