简体   繁体   中英

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

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.

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.

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.

Thanks.

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;
}

In the child process, before calling exec , you need to close the standard output stream.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM