More Pipes
Prof. Brian D. Davison
Computer Science & Engineering, Lehigh University
Announcements
- Reminder Project 8 (last one!) is due Thursday.
- Reminder: Final exam is scheduled for Wednesday May 4, noon-3pm in Packard 416
- Contact me if you already have two finals scheduled for that day to arrange to take the exam earlier.
- Today
- Return p7: range 28-100, mean 89
- Short Quiz 10
- More Pipes
- Course Evaluation
System Programming
- UNIX has three types of data channels, but one type of i/o interface
- Disk/device files -- use open() to connect, use read() and write() to transfer data
- pipes -- use pipe() to create, fork() to share, and use read() and write() to transfer data
- sockets -- use socket(), listen(), accept(), connect() and use read() and write() to transfer data
- To learn about sockets and how other aspects of networking work, consider taking CSE342.
bc: a UNIX calculator
- bc is an arbitrary precision calculator. It has variables, loops, functions, etc.
- Try it -- it supports normal order of operations.
- But use ps to see what's going on...
bc: a UNIX calculator
- bc is an arbitrary precision calculator. It has variables, loops, functions, etc.
- Try it -- it supports normal order of operations.
- But use ps to see what's going on...
- bc does not do calculations -- dc does the calculations
Client-server model
- dc provides a service (calculation)
it has a well-defined language (RPN)
it communicates via stdin and stdout
- bc provides a user interface and uses dc's services
bc is called a client of dc
Coding bc
- More pipe(), fork(), dup(), exec()
int todc[2], fromdc[2];
pipe(todc); pipe(fromdc);
fork();
if ({parent}) {
close(todc[0]);
close(fromdc[1]);
repeat
readline from user
convert
write(todc[1], cmd, length)
read(fromdc[0], reply)
printf to user
popen() -- making processes look like files
- recall fopen() -- create buffered stream to a file
FILE *fp = fopen("stuff", "r");
c = getc(fp); fgets(buf, len, fp); fscanf(fp, ...)
fclose(fp);
- meet popen(cmds, how) -- creates a buffered stream to a program
FILE *fp = popen("ls", "r");
fgets(buf, len, fp);
pclose(fp);
- Args to popen() -- any shell command, "r" or "w", not "a"
Writing popen() featuring fdopen()
- Idea: create a pipe to a program and convert that pipe into a FILE *
- Fact: a pipe is a pair of file descriptors. To convert a file descriptor into a FILE *, use fdopen(fd, "r");
- Approach:
pipe(p);
fork();
if (child) {
close(p[0]);
dup2(p[1],1);
close(p[1]);
execl("/bin/sh", "sh", "-c", cmd, NULL);
} else { // parent
close(p[1]);
fp = fdopen(p[0], "r");
return fp;
}
- Now we can write popen().
Course Evaluation
- Additional questions:
- How prepared are you for future work requiring programming in C?
- How much have you learned about using and programming in UNIX?
- What did you like best about the course?
- What should be changed for the next time the course is taught?