Advertisement

Redirecting IO

Started by October 26, 2002 08:34 AM
5 comments, last by Viro 22 years ago
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.
  
	//redirect output

					fd = open(filename, O_WRONLY|O_CREAT, S_IRWXU|S_IRWXG|S_IRWXO);
						
					close(1);
					dup(fd);
					close(fd);
  
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.
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:
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.
Advertisement
Got it sorted!!!!!!
"Linux is not about free software, it is about community," -- Steve Balmer, Microsoft Chief Executive.
PS "Viro" is Linus'' handle (or is it Alan Cox?)
Try Al Viro''s... noob ;-P
Linus uses the handle Viro?
"Linux is not about free software, it is about community," -- Steve Balmer, Microsoft Chief Executive.
Advertisement
hahaha!

AL VIRO IS NAMED AL VIRO.
LINUS IS NAMED LINUS.

*sigh*

This topic is closed to new replies.

Advertisement