Exercise: fork return data


Create a script that will go over a list of numbers and does some computation on each number.


examples/fork/compute.py
import sys
import time
from mymodule import calc

def main(n):
    results = {}
    print(f"do 1-{n}")
    for ix in range(1, n):
        results[ix] = calc(ix)
    return results

if __name__ == '__main__':
    if len(sys.argv) < 2:
        exit(f"Usage: {sys.argv[0]} NUMBER")

    start = time.time()
    results = main(1+int(sys.argv[1]))
    end = time.time()
    total = sum(results.values())
    print(f"Total: {total}")
    print("Elapsed time: {}".format(end-start))

Allow the child process to return data to the parent process. Before exiting from the child process, serialize the data-structure you want to send back and save in a file that corresponds to the parent process and the child process. (eg. created from the PID of the paraent process and the PID of the child process) In the parent process, when one of the children exits, check if there is a file corresponding to this child process, read the file and de-serialize it.