簡體   English   中英

使用fork和exec啟動過程,同時將stdout重定向到/ dev / null

[英]launch process with fork and exec while redirecting stdout to /dev/null

我有一個非常具體的問題,經過大量搜索后無法找到答案。 我有一個Linux程序。 它的工作是在通過網絡接收到特定消息時啟動另一個輔助可執行文件(通過fork()exec() )。 我無權修改輔助可執行文件。

我的程序將所有TTY都打印到stdout,通常我通過./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;
}

在子進程中,在調用exec之前,您需要關閉標准輸出流。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM