//redirect output
fd = open(filename, O_WRONLY|O_CREAT, S_IRWXU|S_IRWXG|S_IRWXO);
close(1);
dup(fd);
close(fd);
Redirecting IO
I''m writing a shell, and I''m trying to implement the IO redirection features.
I''ve managed to redirect STDIO to and from a file. THe only problem now is that once I''ve redirected, I''ve lost all contact with stdio.
My code for redirecting output. It does redirect stdout to fd, but how do I get stdout to be stdout after that?
"Linux is not about free software, it is about community," -- Steve Balmer, Microsoft Chief Executive.
October 26, 2002 08:53 AM
Save the old stdout filehandle and dup2 it back into descriptor 1 when you''re done with the new one.
The whole code should look something like:
If you''re using stdio streams as well, be careful lest you interfere with (or be interfered with by) its buffering.
Also, I can''t really think of any good reason to do this.. if you''re trying to redirect the standard IO of a child process, just do so after the fork() and you won''t affect the parent''s streams.
The whole code should look something like:
int new_file=blah_blah();int old_stdout=dup(1);dup2(new_file,1); // No need to close first, dup2 will do itclose(new_file);// Do stuffdup2(old_stdout,1);close(old_stdout);
If you''re using stdio streams as well, be careful lest you interfere with (or be interfered with by) its buffering.
Also, I can''t really think of any good reason to do this.. if you''re trying to redirect the standard IO of a child process, just do so after the fork() and you won''t affect the parent''s streams.
Got it sorted!!!!!!
"Linux is not about free software, it is about community," -- Steve Balmer, Microsoft Chief Executive.
Linus uses the handle Viro?
"Linux is not about free software, it is about community," -- Steve Balmer, Microsoft Chief Executive.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement