Pipes for Process Communication
Exercise. Write a C program factorial.c that calculates the factorial of a positive number
given as an argument in the command line, and prints out the answer. Execution example:
bash$ factorial 50
30414093201713378043612608166064768844377615689605120
This is easy to code, except that the product 1*2*3* ... *50 is much too large for an
int or a long in C. However, there is a neat program called bc that handles
any size integers. Try the following:
bash$ bc
1*2*3*4*5*6*7*8*9*10*11*12*13*14*15
1307674368000
quit
bash$
User input is marked in italic. Using pipes, we can use bc from inside our factorial
program. Your program should:
- Create a pipe
- fork/exec the bc program with its stdin redirected to the read
end of pipe
- Parent writes 1*2*3*...*50\n (or whatever the number argument is) to the write end of the
pipe
- Child reads that, computes, and writes its answer to stdout
- Parent writes quit\n to the write end of the pipe
- Child reads that and terminates
- Parent waits for the child to terminate, then terminates itself