mdevico mdevico - 21 days ago 5
Linux Question

launch process with fork and exec while redirecting stdout to /dev/null

I have a very specific problem for which I am unable to find the answer after numerous searches. I have a linux program. It's job is to launch another secondary executable (via

fork()
and
exec()
) when it receives a specific message over the network. I do not have access to modify the secondary executable.

My program prints all its TTY to stdout, and I typically launch it via
./program > output.tty
The problem I have is that this second executable is very verbose. It simultaneously prints to stdout while also putting the same TTY in a log file. So my
output.tty
file ends up containing both output streams.

How can I set things up such that the secondary executable's TTY gets redirected to
/dev/null
? I can't use
system()
because I can't afford to wait for the child process. I need to be able to fire and forget.

Thanks.

Answer

In the child process, before calling exec, you need to close the standard output stream.

pid_t pid =fork();
if (pid == 0) {
    close(1);
    // call exec
} else if (pid > 0) {
    // parent
}