0

I am writing my own shell in C. It's fairly simple, but I want to implement three more commands. First being commands, with or without arguments, whose output is redirected to a file. Second being, a command, with or without arguments, whose output is appended to a file. Lastly, a command, with or without arguments, whose input is redirected from a file.

All of these commands can be implemented using the syscalls freopen(), dup() and dup2().

An example of the first command could be ls -l > fileName.txt. This should take the output of the command and put it in fileName.txt.

An example of the second command could be ls -l >> fileName.txt. This should take the output of the command and append it to whatever is in the file fileName.txt.

An example of the last command could be bc < file. This takes the output of the command and put it in the named file.

This shouldn't be too hard to implement, but for some reason I don't know how to do it and am having some serious trouble. Could someone help me out?

user3268401
  • 319
  • 1
  • 7
  • 21
  • "<" ">" redirects the stdin stdout of an executable file. so parse the argument for filename, open it, redirect the stdin/stdout from/to the file. you can use ref http://stackoverflow.com/questions/584868/rerouting-stdin-and-stdout-from-c...also >> is append so you can decide at file open (fopen in mode a+) ref http://man7.org/linux/man-pages/man3/fopen.3.html –  Apr 18 '14 at 19:30

1 Answers1

1

I'd stick to raw system calls. Forget freopen() and use open(). The stdio routines work with FILE* streams while the syscalls work with integer file descriptors. Mixing the two guarantees serious trouble. ;-)

Redirection goes in 4 steps

  • open() file to redirect to/from, returns an fd
  • close() file to redirect, 0 for stdin, 1 for stdout
  • dup(fd) fd was returned by open() in the 1st step
  • close(fd) you don't need it enymore

The trick is that dup() returns the lowest available integer for a new file descriptor. If you've just closed stdout 1, it will return 1, and suddenly your stdout is pointing to the previously opened file.

SzG
  • 12,333
  • 4
  • 28
  • 41
  • I'd suggest `dup2` instead of `dup` since it does exactly what you want in one atomic operation. – Flexo Apr 18 '14 at 21:02
  • Yes. But the project is obviously about learning, so I'd actually suggest trying both. :-) – SzG Apr 18 '14 at 21:04