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!!
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.