How To Run 2 Child Processes, But Run One Subsequent To Another In C?
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!!
Answer
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.
Related Questions
- → OctoberCMS Backend Loging Hash Error
- → "failed to open stream" error when executing "migrate:make"
- → OctoberCMS - How to make collapsible list default to active only on non-mobile
- → Create plugin that makes objects from model in back-end
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → How to install console for plugin development in October CMS
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → How to update data attribute on Ajax complete
- → October CMS - Conditionally Load a Different Page