// create a number N of child processes specified via commandline argument // each child sleeps for a random time between 1 and 5 seconds // each child prints its PID and the time it slept // the parent waits for all children to finish and then exits #include #include #include #include int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "Usage: %s \n", argv[0]); return 1; } int n = atoi(argv[1]); for (int i = 0; i < n; i++) { pid_t pid = fork(); if (pid < 0) { perror("fork"); return 1; } if (pid == 0) { // child srand(getpid()); int sleep_time = 1 + rand() % 5; printf("Child %d with PID %d will sleep for %d seconds\n", i, getpid(), sleep_time); sleep(sleep_time); printf("Child %d with PID %d slept for %d seconds\n", i, getpid(), sleep_time); return 0; } } // parent for (int i = 0; i < n; i++) { int status; wait(&status); } return 0; }