

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


Solution to homework 1: Processes and Threads
Solution: A program is a collection of source files in some high level language that you write to do some function, for example, C++ files that implement sorting lists. An executable is the file that the compiler creates from these source files containing machine instructs that can execute on the CPU. A process is the active execution of the executable on the CPU and in the memory. It includes the memory management information, the current PC, SP, HP, registers, etc.
#include <sys/types.h> #include <unistd.h> #include <sys/wait.h> #include <stdio.h> #include <signal.h>
main() { pid_t pid1, pid2;
printf("PARENT: forking child1\n");
if ((pid1 = fork()) == 0) { // Child process printf("CHILD1: running\n"); sleep(5); printf("CHILD1: exiting\n"); exit(0); } else { printf("PARENT: forking child2\n"); if ((pid2 = fork()) == 0) { // Child process printf("CHILD2: running\n"); while (1); printf("CHILD2: exiting\n"); exit(0); } else { printf("PARENT: waiting for child1 to finish\n"); waitpid(pid1, 0, 0); printf("PARENT: Child1 dead\n"); fflush(stdout); if (!kill(pid2, SIGHUP)) { printf("PARENT: Killed child2\n"); } } } }
// Output // // > run // PARENT: forking child // PARENT: forking child // CHILD1: running // PARENT: waiting for child1 to finish // CHILD2: running // CHILD1: exiting // PARENT: Child1 dead // PARENT: Killed child