简体   繁体   中英

Reading stdout/stderr from an exec()'ed process in a daemon

I have a daemon process where I need to fork()/exec() some new processes and then read the child processes stdout/stderr.

My problem is that the parent is a daemon where stdout and stderr are closed. Is there anyway to do this? Do I have to open a shell?

int status;
pipe(pipefd_stdout);
pipe(pipefd_stderr);

pid_t pid = fork();
if (pid == 0)
{   
    close(pipefd_stdout[0]);    // close reading end in the child
    close(pipefd_stderr[0]);    // close reading end in the child

    dup2(pipefd_stdout[1], 1);  // send stdout to the pipe
    dup2(pipefd_stderr[1], 2);  // send stderr to the pipe

    execvpe(cmd, (char**)args, (char**)env);
}
else
{
    // parent ...

    waitpid(pid, &status, 0);

    close(pipefd_stderr[1]);  
    close(pipefd_stdout[1]);  
}

A shell wouldn't help here anyway. You need to create one or more pipes (depending in whether you want the output to stdout/stderr conflated into one stream or not) using pipe() and then dup() (or similar) and close() to put the appropriate file descriptors into place. The call to pipe() precedes the fork() , the calls to dup() and close() come after.

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