gpt4 book ai didi

c - 使用 fork 和 exec 启动进程,同时将 stdout 重定向到/dev/null

转载 作者:太空狗 更新时间:2023-10-29 11:35:50 27 4
gpt4 key购买 nike

我有一个非常具体的问题,经过多次搜索后我无法找到答案。我有一个linux程序。它的工作是在通过网络接收到特定消息时启动另一个辅助可执行文件(通过 fork()exec())。我无权修改辅助可执行文件。

我的程序将其所有 TTY 打印到标准输出,我通常通过 ./program > output.tty 启动它 我遇到的问题是第二个可执行文件非常冗长。它同时打印到标准输出,同时还将相同的 TTY 放入日志文件中。所以我的 output.tty 文件最终包含两个输出流。

我如何设置才能将辅助可执行文件的 TTY 重定向到 /dev/null?我不能使用 system() 因为我不能等待子进程。我需要能够开火就不管了。

谢谢。

最佳答案

在子进程中使用 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;
}

关于c - 使用 fork 和 exec 启动进程,同时将 stdout 重定向到/dev/null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40667254/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com