Answer of exercise 10

If the command line ends with &, we do not call wait in the parent process and immediately continue with the next iteration of the loop. But there is one difficulty: the parent may now have multiple children executing at the same time (the commands in the background which haven’t terminated yet, plus the last synchronous command), and wait could synchronize with any of these children. Thus, for synchronous command, wait must be repeated until the recovered child is the one actually executing that command.

while true do let cmd = input_line Pervasives.stdin in let words, ampersand = parse_command_line cmd in match fork () with | 0 -> exec_command words | pid_son -> if ampersand then () else let rec wait_for_son () = let pid, status = wait () in if pid = pid_son then print_status "Program" status else let p = "Background program " ^ (string_of_int pid) in print_status p status; wait_for_son () in wait_for_son () done
* * *