Fork redirect child output c/c++

Started by
5 comments, last by user0 11 years, 11 months ago
I am tring to prevent the child of the fork to write to the standard cout. If I redirect it cout I get a segfault probably because the parent gets redirected as well or I could be doing it wrong I tried it like the example here http://www.cplusplus.com/reference/iostream/ios/rdbuf/. I have tried looking it up and came across dup and pipes but I dont know if thats what I need and how to use them. Can someone point me in the right direction please?
Advertisement
Are you trying to prevent child output completely, or send it to the parent process? And just checking: you only require a solution for a UNIX system?
What I am trying todo right now is to prevent the child output completely. Yea unix/linux c c++.
I think what you want to do is open /dev/nul (or your system's equivalent) in the child process and then dup2() that fd over the top of STDERR_FILENO and STDOUT_FILENO. This needs to be done before you load the child with e.g. execv().


/* Error checking omitted */
if (fork() == 0)
{
/* We're the child */
int fd = open("/dev/nul", /* see man pages :) */);
dup2(fd, STDERR_FILENO);
dup2(fd, STDOUT_FILENO);

execv(child_path, child_argv);
}


I think simply closing STDERR_FILENO and STDOUT_FILENO is wrong as if the child opens a file, the fd assigned to that file could be one of those values, which would cause all kinds of weird effects when writing to stdout/stderr.
Thank You but is there any way I can do it without the exec that way I can keep whats in memory?
In practice it might be ok if you were to do something other than call one of the exec() functions after the dup2()s.

However the spec suggests (to me, at least) that we should call one of the exec() functions in the child soon after it is forked, and only async-signal-safe calls be made in the child before that time. dup2() is async-signal-safe.
Thank you for your help its working exactly as I need it now!

This topic is closed to new replies.

Advertisement