I have a program reading from stdin and whilst doing this it sometimes need to fork() and execute a command asynchronously. Sometimes shortly after this fork (probably whilst the command is running), the parent seems to lose data read from stdin. If only a single byte is lost, the program will never recover.
The man page for fork() says that the child inherits copies of the parent's set of open file descriptors, but trying close(STDIN_FILENO) just after fork() and before execvp() doesn't help.
My program basically does:
if (we_need_to_run_a_command_asynchronously) {
if (!fork()) {
close(STDIN_FILENO);
char *args[] = { "command", "arg", "etc", 0 };
setpriority(PRIO_PROCESS, 0, -19);
execvp("command", args);
exit(0); // Ignore errors
}
}
How can I be sure that the child cannot interfere with the parent's stdin (or anything else belonging to the parent)? The command executed is typically a shell script.
I don't know exactly what goes wrong in my program, but it runs fine as long as it doesn't run any commands. Only sometimes (not always) just after it runs a command, the data that it reads from stdin somehow gets corrupted, which is why I suspect that the problem is related to stdin after fork().
Instead of closing stdin you could open another file and use dup2 to duplicate the new file descriptor onto stdin. If you opened
/dev/nulland redirected it to stdin after theforkand before andexecthe child will not interfere with the parent's stdin.