Introduction
结合Unix的系统工具,甚至可以将输入输出流通过fd传给子进程。下面的需求便是通过nameless pipes将数据传递给Unix的sort和grep工具。
Requirement
This problem will require you to write two different, but similar, programs that each spawn a child, let the child process load itself with a Linux/UNIX type command (the grep and sort commands will be used in this request), and then send data to and retrieve data from the child process. Each of your programs will need to:
Create 2 nameless pipes
- Create a child process
- The parent will be responsible for managing any data files that the child command will need sent via the pipe
- The parent will collect all output from the child command sent through the pipe, process it as required and write required results to the standard output
- The parent will terminate with success when the pipe being read from the child command shows EOF
Perform the appropriate channel management with the processes’ standard IO channels and the pipe channels to create a circular connection through the UNIX command - standard input to the command child will be sent as output from the parent
For the sort command
from your parent process, open the file for reading
- Read each line of the file and write it into (the parent’s) OUT pipe to the child process that has exec’d sort
- Read the file back from the child running sort from the (parent’s) IN pipe, and write the required results to stdout (or a file if you choose)
- sort must sort the data sent by the parent first by phone number area code and then by last name within each area code
- Your equired output will be a summary of the sorted results returned by the child running sort that consists of a listing of each unique area code and the number of people found in the data sent to sort for that code
For the grep command
from your parent process, open the file for reading
Read each line of the file and write it into (the parent’s) OUT pipe to a child process that exec’d grep
- The child process running grep must filter its incoming lines, looking for any line that has the string “123” in it
- The child process running grep must write back each matching line to the parent process by writing it into the (parent’s) IN pipe
- You (the parent) must read back grep’s output from your IN pipe and print out a single number indicating how many lines had the matching string as your report. You must count the lines returned by grep in your parent process (do not have grep count the lines)
- You must now repeat this grep exercise using the file
Summary
熟悉父子进程和nameless pipe的话,这个需求难度并不高。不过需要注意的是,对EOF的处理,稍有不慎,程序将卡死在sort和grep中,无法退出。