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

时间:2016-11-18 00:05:50

标签: c linux process

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

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

如何进行设置以使辅助可执行文件的TTY重定向到/dev/null?我无法使用system(),因为我无法等待子流程。我需要能够解雇并忘记。

感谢。

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:1)

在子进程中,在调用exec之前,您需要关闭标准输出流。

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