Belajar
← All lessons

How processes and threads work

Run a command: fork, then exec

Shell
Kernel
Child

shell.c

char *line = readline("$ ");   // the shell reads what you typedchar *argv[] = { line, NULL }; pid_t pid = fork();if (pid == 0) {          // only the child takes this branch  execvp(argv[0], argv); // replaces this program, never returns  _exit(127);            // only reached if exec failed}int status;waitpid(pid, &status, 0); // the parent sleeps until 413 exitsprintf("%d\n", WEXITSTATUS(status));

program.c

// the program you namedint main(int argc, char **argv) {  list(argc > 1 ? argv[1] : ".");  return 0;              // returning from main calls exit(0)}

Processes copy memory, threads share it so one crash means different things

Run A and B asTwo processesTwo threads
Memory

Sharing has a price: two threads doing count++ at the same moment can lose an update, so real code uses a lock

procs.c

int count = 0;      // same address in both processes pid_t pid = fork();if (pid == 0) {  count++;          // B writes its own copy  *(int *)0 = 1;    // B crashes} else {  count++;          // A is the parent}

threads.c

int count = 0;      // one copy, shared by every thread void *b(void *arg) {  count++;  *(int *)0 = 1;    // B crashes  return NULL;} pthread_t t;pthread_create(&t, NULL, b, NULL);count++;            // A and B change the same count// SIGSEGV kills the whole process

fork() in a loop doubles the processes every pass

Times around the loopn = 0
Process tree pstree
processes
children made
hi printed

PIDs here follow the order of each pass. On a real machine the scheduler decides who forks first

loop.c

int n = N;for (int i = 0; i < n; i++)  fork();           // every process alive runs fork() hereprintf("hi\n");    // runs once in every process

Topics

Next: How virtual memory works

Open lesson