3.9 Exercise: Process Fans

Team-FLY

The exercises in this section expand on the fan structure of Program 3.2 through the development of a simple batch processing facility, called runsim . (Modifications in Section 14.6 lead to a license manager for an application program.) The runsim program takes exactly one command-line argument specifying the maximum number of simultaneous executions. Follow the outline below for implementing runsim . Write a test program called testsim to test the facility. Suggested library functions appear in parentheses.

  1. Write a program called runsim that takes one command-line argument.

  2. Check for the appropriate command-line argument and output a usage message if the command line is incorrect.

  3. Initialize pr_limit from the command line. The pr_limit variable specifies the maximum number of children allowed to execute at a time.

  4. Initialize the pr_count variable to 0. The pr_count variable holds the number of active children.

  5. Execute the following main loop until end-of-file is reached on standard input.

    1. If pr_count is pr_limit , wait for a child to finish ( wait ) and decrement pr_count .

    2. Read a line from standard input ( fgets ) of up to MAX_CANON characters and execute a program corresponding to that command line by forking a child ( fork , makeargv , execvp ).

    3. Increment pr_count to track the number of active children.

    4. Check to see if any of the children have finished ( waitpid with the WNOHANG option). Decrement pr_count for each completed child.

  6. After encountering an end-of-file on standard input, wait for all the remaining children to finish ( wait ) and then exit.

Write a test program called testsim that takes two command-line arguments: the sleep time and the repeat factor. The repeat factor is the number of times testsim iterates a loop. In the loop, testim sleeps for the specified sleep time and then outputs a message with its process ID to standard error. Use runsim to run multiple copies of the testsim program.

Create a test file called testing.data that contains commands to run. For example, the file might contain the following lines.

 testsim 5 10 testsim 8 10 testsim 4 10 testsim 13 6 testsim 1 12 

Run the program by entering a command such as the following.

 runsim 2 < testing.data 
Team-FLY


Unix Systems Programming
UNIX Systems Programming: Communication, Concurrency and Threads
ISBN: 0130424110
EAN: 2147483647
Year: 2003
Pages: 274

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net