Synchronization, multi-processing, parallelism, and concurrency
- All central themes of the course, and all very powerful features.
- Very difficult to understand and get right, and all kinds of concurrency issues and race conditions can appear unless you code very carefully.
- Consider the following program, which is a gesture to where your Assignment 4 shell will end up when it's all done (code for entire program can be found right here):
static void reapChild(int sig) {
pid_t pid;
while (true) {
pid = waitpid(-1, NULL, WNOHANG);
if (pid <= 0) break;
printf("Job %d removed from job list.\n", pid);
}
exitUnless(pid == 0 || errno == ECHILD, kWaitFailed,
stderr, "waitpid failed within reapChild sighandler.\n");
}
int main(int argc, char *argv[]) {
exitIf(signal(SIGCHLD, reapChild) == SIG_ERR, kSignalFailed,
stderr, "signal function failed.\n");
for (size_t i = 0; i < 3; i++) {
pid_t pid = fork();
exitIf(pid == -1, kForkFailed,
stderr, "fork function failed.\n");
if (pid == 0) {
char *listArguments[] = {"date", NULL};
exitIf(execvp(listArguments[0], listArguments) == -1,
kExecFailed, stderr, "execvp function failed.\n");
}
snooze(1); // represents meaningful time spent
printf("Job %d added to job list.\n", pid);
}
return 0;
}