使用fork和exec启动过程,同时将stdout重定向到/dev/null [英] launch process with fork and exec while redirecting stdout to /dev/null
问题描述
我有一个非常具体的问题,经过大量搜索后无法找到答案.我有一个Linux程序.它的工作是在通过网络接收到特定消息时启动另一个辅助可执行文件(通过 fork()
和 exec()
).我无权修改辅助可执行文件.
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.
我的程序将其所有TTY打印到stdout,通常我通过启动它.output.tty
我的问题是第二个可执行文件非常冗长.它同时打印到标准输出,同时还将相同的TTY放在日志文件中.因此,我的 output.tty
文件最终包含了两个输出流.
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.
如何进行设置,以使辅助可执行文件的TTY重定向到/dev/null
?我无法使用 system()
,因为我无力等待子进程.我需要能够开火并忘记.
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.
谢谢.
推荐答案
在子进程中,使用 dup2()
将输出重定向到文件.
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;
}
这篇关于使用fork和exec启动过程,同时将stdout重定向到/dev/null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!