• Your shell must support I/O redirection for standard input and standard output:... • The general idea is to set up standard input or output before calling exec... – system calls use “f
Trang 1Discussion Section
10/09/09
Trang 2Issues involved with Programming a Shell
Trang 5• Your shell must support I/O redirection for standard input and standard output:
Trang 6• The general idea is to set up standard input (or output) before calling exec().
Trang 7• We will deal with Unix directly via system calls (not via libraries).
– open, close, read, write,
– system calls use “file descriptors” to refer to open files.
Trang 9this
Trang 10File Descriptor Table
Trang 11• When calling Unix I/O system calls, you give them an open file descriptor:
– write(fd,”hello”,5);
– read(fd,buff,22);
– close(fd);
• File descriptors can refer to open files, pipes, fifos, sockets, etc.
Trang 13• For files, read will always read nbytes unless it
hits the end of the file first.
– reading from pipes and sockets is a little different.
Trang 15• Return value is the number of bytes written. Negative number means an error occurred.
• Write can block!
– max capacity of a pipe has been reached.
– network buffer full.
• Typically doesn't block when writing to a file
Trang 16• dup2(fd,newfd) will duplicate a file descriptor,
the new descriptor will be newfd
Trang 17Using dup2()
• dup2 can be used to assign an open file to stdin:
– dup2(fd, 0);
– /* or dup2(fd, STDIN_FILENO); */
Trang 18Using dup() continued.
Trang 19Example: sortfile Redirecting STDIN
• We want to make a command that will sort a file for us (never mind that sort will do this without any help ).
– sortfile somefile
• sortfile.c will
– open somefile
– dup2 the new file descriptor to STDIN_FILENO – exec the sortcommand.
Trang 20sortfile.c (abbreviated)
Trang 21Example: logusers Redirecting STDOUT
Trang 22logusers.c (abbreviated)
Trang 24command, the result is a sorted list of all files
whose names contain “fred”.
Trang 26writing to the pipe.
Trang 27Calling pipe()
fds[1]can be used to write to the pipe.
Trang 28• child process attaches the reading end of the pipe to stdin.
• parent exec's ls
• child exec's sort
Trang 29sortedls.c (abbreviated)
Trang 30• ls ‐al | grep '.c' | cut ‐c30‐ | sort ‐n > foo
Trang 32– fork, and child will become ls
– Have child create pipe(), and fork().
• child execs ls.
• grandchild processes something (in the same way).
Trang 33• how processes communicate with each other
– find info from:
– http://linux.about.com/od/commands/l/blcmdl7_ signal.htm
Trang 37<<An Introduction to GCC>>
http://www.network‐theory.co.uk/docs/gccintro/
Trang 38or just
man turnin
Trang 39answer?
Thank you!