DEMO EXECUTABLES (see runtime.txt)
Write a C program and compile it into a.out that deos the following when run:
The process a.out is given 2 argument (numbers), e.g., a.out 5 100.
It calls fork() the same number of times as the 1st given argument to create child processes.
The parent process a.out waits (for any child to exit).
Each child process performs a loop that:
gets a random integer ranging from 0 to 9
adds the number to a sum
displays its process ID and the current sum
sleeps for 1 second
loop again, until the accmumulated sum reaching (or over) a supposed goal number (100, or, the 2nd argument given to the parent process, a.out).
The child exits using the sum as the return exit code in order to notify the parent process.
The parent process then prints out: 1. its process ID, 2. the exiting child process ID, 3. the sum the exiting child got.
One by one, all child processes will reach the goal and exit.
OS Service Calls
You will need the system/library calls listed below in your code. Therefore, you need to first understand what they do and how they are called. Study: 1. Online unix manual page, 2. Marshall’s text, 3. Kerrisk’s book, 4. Online resources such as UNIX Help for Users which is linked from the class webpage.
fork() spawning a child process
exit() exiting (termination)
wait() waiting for a (any) child process to exit
atoi() “ascii (string) to integer” conversion
getpid() getting its own process ID
sleep() suspending itself for a number of seconds
srand() seeding the randomization
rand() randomization (getting a random number)
printf() (Yay, printf allowed!)
perror() (handy when errors occur at system calls)
execl() (for bonus part)
sprintf() (for bonus part: “string-printf” to bring integers into string
Bonus Part (2 extra points)
Use the system call execl() to execute child process code (to depart from parent code).
Hint: compile the child code separately to a different executable. That is, name it differently (such as b.out) — and a variable goal number can now be supplied to children from parent code (given by the user originally), right? How?
Add to the code such that the parent will be able to force all other child processes (as soon as it can) to terminate once receiving the sum from the winning child?