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?
Fork redirect child output c/c++
Started by jeff8j, May 27 2012 06:22 AM
6 replies to this topic
Ad:
#4 Members - Reputation: 2040
Posted 27 May 2012 - 07:44 AM
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().
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.
/* Error checking omitted */
if (fork() == 0)
{
/* We're the child */
int fd = open("/dev/nul", /* see man pages <img src='http://public.gamedev.net//public/style_emoticons/<#EMO_DIR#>/smile.png' class='bbc_emoticon' alt=':)' /> */);
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.
Edited by edd², 27 May 2012 - 07:47 AM.
#6 Members - Reputation: 2040
Posted 27 May 2012 - 05:52 PM
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.
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.
Edited by edd, 27 May 2012 - 05:53 PM.






