This is a fragment of my program that is working, but the machine that corrects it tries this:
strace ./watcher echo 2>&1 > /dev/null | grep wait | cut -c1-4
The expected output is:
wait
But my program prints a random number of waits (like this):
wait
wait
wait
wait
wait
wait
This is the code:
// creates a child process
pid_t process_id;
int status;
process_id = fork();
switch(process_id)
{
case -1: // Error while making the forkFork failed
fprintf(stderr, "Fork failed.\n");
break;
case 0: // Child process.
execvp(command[0], command); // command here is char**
// execvp only returns when error.
Error(argv[0], 1); // Error just prints the error
exit(1);
break;
default: // Parent process.
while(!waitpid(process_id, &status, WNOHANG));
finished(status); // It prints how the process has finished.
}
I think the problem is in that while with the waitpid inside, that is generating a lot of waits. But if I remove it and leave the waitpid alone, I receive this output:
standard input: Input/output error
Is there a way to make only one wait call without getting that error?
You might try to not set WNOHANG
on the call to waitpid()
.
This would make waitpid()
block until the child terminates.