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.
Redirect All Output to /dev/null There are two ways to do this. The string >/dev/null means “send stdout to /dev/null,” and the second part, 2>&1 , means send stderr to stdout. In this case you have to refer to stdout as “&1” instead of simply “1.” Writing “2>1” would just redirect stdout to a file named “1.”
The way we can redirect the output is by closing the current file descriptor and then reopening it, pointing to the new output. We'll do this using the open and dup2 functions. There are two default outputs in Unix systems, stdout and stderr. stdout is associated with file descriptor 1 and stderr to 2.
You write to /dev/null every time you use it in a command such as touch file 2> /dev/null. You read from /dev/null every time you empty an existing file using a command such as cat /dev/null > bigfile or just > bigfile. Because of the file's nature, you can't change it in any way; you can only use it.
/dev/null in Linux is a null device file. This will discard anything written to it, and will return EOF on reading. This is a command-line hack that acts as a vacuum, that sucks anything thrown to it.
In child process use dup2()
to redirect the output to a file.
int main(int argc, const char * argv[]) {
pid_t ch;
ch = fork();
int fd;
if(ch == 0)
{
//child process
fd = open("/dev/null",O_WRONLY | O_CREAT, 0666); // open the file /dev/null
dup2(fd, 1); // replace standard output with output file
execlp("ls", "ls",".",NULL); // Excecute the command
close(fd); // Close the output file
}
//parent process
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With