I'm implementing a shell in C that supports piping, output redirection, and background processing, and a few other commands. I was wondering how I'd go about implementing the output redirection. So, I'd open a file and I'd fork and execute the command. But how would I get stdout into the file? Any help is greatly appreciated.
Close stdin and then open some other file.
close()
open()
Both have man pages.
i too have a question on the topic.
how do i read from keyboard if stdin is actually stdout of another program. an example is less/more: keyboard input still works when they're piped.
This is more of a separate question. You probably should have started a new thread.
If you type "tty", you will see the name of your controlling terminal. If it is, say, /dev/pty/j2, then you could simply open that file to gain access to the keyboard. But it is a lot of work to get the name of your particular terminal, so there is a second way. In the unix environment, a process with a controlling terminal can open the special file /dev/tty and get their own controlling terminal. This won't work if there is no crontrolling terminal such as with a cron job. Even though there is only one file on the system called /dev/tty, each user that opens it will get his or her own keyboard.
However, this may not be a great move to make. Suppose that I have a complicated pipeline of 4 processes. If they all do this at the same time it will be pretty hopeless to get it all straight. And look at all the threads we get where folks need to script the su command and must "expect" to do it. Users tend to dislike programs that do this.
Closing stdin gives me an infinite loop.
Is there a way to maybe modify the file descriptor table so that I replace stdout with the file I've just opened? How would I access the file descriptor table though?
well, i've came across with that problem when i attemped to write a shell. i thought, programs' output should be filtered/processed by shell interpreter first, and then sent to shell screen-output program (in case they're seperate programs) and still be able to catch keyboard input to send programs ctrl+c etc. i've given less & more as examples since they're more common to Unix folks...
however, thanks for the reply.
It works for everyone else. You must have a bug.
open() and close() modify the file descriptor table. No, you cannot bypass them and fiddle with the kernel tables directly.
You need to start with the basics and work your way up. You're trying to write a shell, but you're having difficulty when you open and close files. You should consider a less ambitious project until you get a little bit more experience.
Nevermind. I figured it out for anyone who cares:
open a file
dup2(file, 1)
execute
PS: Thanks for false information and then insulting me.