I have a Makefile that looks something like this:
sometarget:
command_one # calls fork()
command_two
Here's the problem I'm running into when I do make sometarget
:
command_one
starts and eventually calls fork()
.
The child process exec
s something and finishes early, returning control to make
before all the processing of command_one
is done.
command_two
then executes before the parent completes, causing the sequence to fail (as it depends on command_one
finishing completely).
I can change command_one
(the fork() and exec() have to stay, though), and I'd rather not change the Makefile if possible. Is there a way to prevent the child process from returning (on Linux)? I'm thinking the answer is no, but I've been wrong before...
It sounds like your command_one
looks something like this pseudo-code:
main() {
pid_t child = fork(); /* ignore error for sake of example */
if (child) {
/* some work in the parent */
exit;
} else {
/* some work in the child */
}
exit;
}
If you insert a waitpid(2)
or wait(2)
(or any member of the family) immediately before the parent's exit
, it'll make sure both child and parent are finished before make(1)
moves onto the next command. It'll look something more like this:
main() {
pid_t child = fork(); /* ignore error for sake of example */
if (child) {
/* some work in the parent */
exit;
} else {
/* some work in the child */
}
waitpid(child, &status, 0); /* NEW LINE */
exit(&status);
}