Jump to content
  • Advertisement
Sign in to follow this  
jeff8j

Fork redirect child output c/c++

This topic is 2190 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
What I am trying todo right now is to prevent the child output completely. Yea unix/linux c c++.

Share this post


Link to post
Share on other sites
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. Edited by edd²

Share this post


Link to post
Share on other sites
Thank You but is there any way I can do it without the exec that way I can keep whats in memory? Edited by jeff8j

Share this post


Link to post
Share on other sites
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. Edited by e?dd

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!