使用 fork 和 exec 启动进程,同时将标准输出重定向到 /dev/null
launch process with fork and exec while redirecting stdout to /dev/null
我有一个非常具体的问题,经过多次搜索都找不到答案。我有一个 linux 程序。它的工作是在通过网络接收到特定消息时启动另一个辅助可执行文件(通过 fork()
和 exec()
)。我无权修改辅助可执行文件。
我的程序将其所有 TTY 打印到标准输出,我通常通过 ./program > output.tty
启动它 我遇到的问题是第二个可执行文件非常冗长。它同时打印到标准输出,同时还将相同的 TTY 放入日志文件中。所以我的 output.tty
文件最终包含两个输出流。
我如何设置才能将辅助可执行文件的 TTY 重定向到 /dev/null
?我不能使用 system()
因为我不能等待子进程。我需要能够开火忘记。
谢谢。
在子进程中,在调用exec
之前,需要关闭标准输出流。
pid_t pid =fork();
if (pid == 0) {
close(1);
// call exec
} else if (pid > 0) {
// parent
}
在子进程中使用 dup2()
将输出重定向到文件。
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;
}
我有一个非常具体的问题,经过多次搜索都找不到答案。我有一个 linux 程序。它的工作是在通过网络接收到特定消息时启动另一个辅助可执行文件(通过 fork()
和 exec()
)。我无权修改辅助可执行文件。
我的程序将其所有 TTY 打印到标准输出,我通常通过 ./program > output.tty
启动它 我遇到的问题是第二个可执行文件非常冗长。它同时打印到标准输出,同时还将相同的 TTY 放入日志文件中。所以我的 output.tty
文件最终包含两个输出流。
我如何设置才能将辅助可执行文件的 TTY 重定向到 /dev/null
?我不能使用 system()
因为我不能等待子进程。我需要能够开火忘记。
谢谢。
在子进程中,在调用exec
之前,需要关闭标准输出流。
pid_t pid =fork();
if (pid == 0) {
close(1);
// call exec
} else if (pid > 0) {
// parent
}
在子进程中使用 dup2()
将输出重定向到文件。
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;
}