Chapter 3: Processes

Operating Systems · Study Questions
Process conceptfork and execTerminationStates and the PCBSchedulingIPC and pipesMessage passingMobile systems
Sercan KÜLCÜ

Multiple Choice · Process Concept

Question 1: Where Do the Variables Live?

A function contains static int counter; (uninitialized), int *p = malloc(100);, which allocates 100 bytes, and a local int i;. Where in the process’s address space are these three stored, in that order?

A: A static local variable lives for the whole program: in the BSS if it is uninitialized, in the data segment if it has an initial value. The memory from malloc is on the heap, while the pointer p itself is on the stack. The local i is in the function’s stack frame.

Output Question · Process Concept

Question 2: Same Address, Different Value

The program is compiled as a and run twice at the same time with ./a 1 & ./a 10, with ASLR disabled. What can be said about the addresses and values printed? Why?

int x = 0;
int main(int argc, char *argv[]) {
  int d = atoi(argv[1]);
  for (int i = 0; i < 3; i++) {
    x += d;
    printf("%s %p %d\n", argv[1], (void *)&x, x);
    sleep(1);
  }
  return 0;
}
Show answer

Sample output (the order of the lines depends on scheduling):

1 0x404034 1
10 0x404034 10
1 0x404034 2
10 0x404034 20
1 0x404034 3
10 0x404034 30
  • Both processes print the same virtual address: same program, same address-space layout.
  • The values do not affect each other (1, 2, 3 and 10, 20, 30): each process has its own address space; the OS maps the same virtual address to different physical frames.

The program is a single file on disk; the two processes are two separate, active instances of it.

Step-by-Step Trace · Process Creation

Question 3: Short Circuit and fork()

All fork() calls succeed. How many X lines are printed and how many processes are created in total? Draw the process tree. (&& does not evaluate its right side when the left is 0.)

P0

Initially a single process: P0.

P0P1

fork(): P0 creates P1; both continue from line 3.

P0P1P2P3

First fork(): P0 → P2, P1 → P3. In P2 and P3 the return value is 0 → && is false; they skip the second fork and the body.

P0P1P2P3P4P5

In P0 and P1 the first result is ≠ 0 → second fork(): P0 → P4, P1 → P5. In P4 and P5 the result is 0 → the condition is false.

P0P1P2P3P4P5P6P7

The condition holds only in P0 and P1: the fork in the body gives P0 → P6, P1 → P7.

P0P1P2P3P4P5P6P7

All eight processes reach printf: 8 X (order undefined). P0 has 4 children, P1 has 3.

int main(void) {
  fork();
  if (fork() && fork())
    fork();
  printf("X\n");
  return 0;
}

Multiple Choice · Process Creation

Question 4: When Output Goes to a File

The program below is run as ./prog > output.txt. What is the content of output.txt?

printf("A\n");
fork();
printf("B\n");

B: When output is redirected to a file, stdout is fully buffered: "A\n" has not been written yet when fork is called and is copied to the child along with the buffer. Each process writes its own "A\nB\n" buffer in one go when it exits. On a terminal stdout is line buffered, so A would be written before the fork and the output would be A, B, B.

Output Question · Process Creation

Question 5: Globals and Heap Variables

The child and the parent both modify the global g and the heap value *h. What does the program print?

int g = 1;
int main(void) {
  int *h = malloc(sizeof(int));
  *h = 10;
  pid_t p = fork();
  if (p == 0) {
    g += 5; *h += 5;
    printf("child: %d %d\n", g, *h);
    return 0;
  }
  waitpid(p, NULL, 0);
  g *= 2; *h *= 2;
  printf("parent: %d %d\n", g, *h);
  return 0;
}
Show answer
child: 6 15
parent: 2 20
  • After fork, the child’s address space is a copy of the parent’s: data, heap and stack included. h holds the same virtual address in both processes, but on the first write copy-on-write (COW) splits them onto different physical pages.
  • The child sees 1 + 5 = 6 and 10 + 5 = 15; the parent computes 1 × 2 = 2 and 10 × 2 = 20 from its own copies.
  • The order is deterministic: the parent waits for the child with waitpid before it writes.

Multiple Choice · Process Creation

Question 6: When execv() Succeeds

A process called execv("/bin/ls", args) and the call succeeded. Which statement is true?

D: exec does not create a process; it replaces the memory image of the existing process with the new program. The PID, the parent relationship and the open descriptors (those not marked close-on-exec) are kept; the shell’s redirection relies on this. B mixes up the return rule of fork.

Output Question · Process Termination

Question 7: Exit Code and Zombie

What does the program print? In which state does ps show the child during the first 10 seconds? What changes after waitpid?

int main(void) {
  pid_t p = fork();
  if (p == 0)
    exit(300);
  sleep(10);
  int st;
  waitpid(p, &st, 0);
  if (WIFEXITED(st))
    printf("%d\n", WEXITSTATUS(st));
  return 0;
}
Show answer

Output: 44. Only the low 8 bits of the exit status are passed to the parent: 300 mod 256 = 44. Portable programs use 0–255.

  • First 10 seconds: the child has finished but the parent has not called wait yet → zombie (Z, <defunct> in ps). Its memory is freed; its PID and exit status wait in the process table.
  • waitpid collects the status and the kernel removes the entry (reaping): no zombie remains.

Multiple Choice · Process Termination

Question 8: The Child Whose Parent Exits First

The parent with PID 500 has terminated; its child is still running and the system has no subreaper defined. What does getppid() return if the child calls it now?

C: A child whose parent has terminated becomes an orphan, and the kernel immediately re-parents it to init/systemd (PID 1). Since init collects its terminated children with wait, an orphan does not stay a zombie for long when it ends. The child does not terminate on its own when its parent does.

Step-by-Step Trace · States and the PCB

Question 9: The Life of a Process

On a single-CPU system, the events for process P occur in the order listed on the left. In which state is P after each event? How many times does P enter the ready queue and how many times does it wait?

NewTerminatedReadyRunningWaiting

Five-state model: New, Ready, Running, Waiting, Terminated.

NewTerminatedReadyRunningWaiting

PCB allocated, address space prepared: New.

NewTerminatedReadyRunningWaiting

Enters the ready queue (1st time).

NewTerminatedReadyRunningWaiting

The scheduler picked it → Running.

NewTerminatedReadyRunningWaiting

The process is not waiting for anything, its time slice just ran out: it returns to Ready, not to Waiting (2nd time).

NewTerminatedReadyRunningWaiting

Picked again → Running.

NewTerminatedReadyRunningWaiting

It waits for an event (the child’s termination): it gives up the CPU.

NewTerminatedReadyRunningWaiting

The event occurred: it goes to Ready first, not directly to Running (3rd time). There is no Waiting → Running arrow.

NewTerminatedReadyRunningWaiting

Picked → Running.

NewTerminatedReadyRunningWaiting

read(): blocks until a line arrives → Waiting (2nd time).

NewTerminatedReadyRunningWaiting

The keyboard interrupt wakes the process: Ready (4th time).

NewTerminatedReadyRunningWaiting

Picked → Running.

NewTerminatedReadyRunningWaiting

Terminated: it entered the ready queue 4 times, waited 2 times and was dispatched 4 times. Its PCB (zombie) stays until the parent waits.

The OS creates the process (PCB, memory)
admitted
the scheduler dispatches it
time slice expired
dispatched again
waitpid: the child has not finished yet
the child terminated
dispatched
read(): waits for a line from the keyboard
the user pressed Enter
dispatched
exit(0)

Multiple Choice · Scheduling

Question 10: How Many Processes Are Needed?

Processes spend 75% of their time waiting for I/O and are independent of each other. By the model CPU utilization = 1 − pⁿ, how many processes must be in memory for utilization to be at least 90%?

C: We need 0.75ⁿ ≤ 0.10. 0.75⁸ ≈ 0.1001 → utilization 89.99%, just below the target; 0.75⁹ ≈ 0.0751 → 92.5%. B comes from rounding ln 0.1 / ln 0.75 ≈ 8.004 down. Each extra process adds less than the one before.

Classic Question · Scheduling

Question 11: Context-Switch Overhead

A context switch takes 0.1 ms; the ready queue holds 5 CPU-bound processes running round robin, and each uses its whole time slice. For time slices of 2 ms and 20 ms, (a) what percentage of CPU time goes to switches, (b) how long does a process wait at most between two of its slices?

Show answer
time sliceoverhead = s / (q + s)wait = 5s + 4q
2 ms0.1 / 2.1 = 4.76%0.5 + 8 = 8.5 ms
20 ms0.1 / 20.1 = 0.50%0.5 + 80 = 80.5 ms

When a process’s slice ends, 5 switches and the slices of the other 4 processes go by. A small slice improves response time but increases overhead; the slice should be chosen far above the switch time. The main indirect cost is the cooling of the cache and TLB.

Multiple Choice · Interprocess Communication

Question 12: Moving Large Images

A camera process transfers 60 large images per second to a processing process on the same machine. Which method has the lowest copying cost, and what is its price?

A: Once shared memory is set up, the data does not pass through the kernel; both processes see the same physical pages. The price: the processes themselves must ensure who writes when (lock, semaphore). In a pipe or a message queue every message is copied into the kernel and out of it; in return the kernel provides the synchronization.

Step-by-Step Trace · Interprocess Communication

Question 13: Reading a Pipe in Pieces

What does the child print? What would happen if the child had forgotten close(fd[1]) on line 6?

pipe buffer (in kernel)open writers: 1

pipe: read end 3, write end 4 (the first free numbers). The buffer is empty.

pipe buffer (in kernel)open writers: 2

fork: the child inherits both ends; now two write ends are open.

pipe buffer (in kernel)open writers: 1

The child closes the write end, the parent closes the read end. If the child called read on the empty pipe, it would block until data arrives.

pipe buffer (in kernel)hello␣worldopen writers: 1

The parent writes the 11 bytes with a single write (writes smaller than PIPE_BUF are not split).

pipe buffer (in kernel)hello␣worldopen writers: 1read → 4buf:hell

read takes at most 4 bytes: "hell".

pipe buffer (in kernel)hello␣worldopen writers: 1read → 4buf:o␣wo

The next 4 bytes: "o wo".

pipe buffer (in kernel)hello␣worldopen writers: 1read → 3buf:rld

Only 3 bytes remain: read returns 3 without waiting.

pipe buffer (in kernel)hello␣worldopen writers: 0

The parent closes the write end: the pipe has no open write end left. (This step may also happen before the reads; the output does not change.)

pipe buffer (in kernel)hello␣worldopen writers: 0read → 0buf:

Empty pipe and no writer → read returns 0 (end of file) and the loop ends. If the child had forgotten line 6, its own write end would stay open and this read would block forever.

int main(void) {
  int fd[2]; char buf[4];
  ssize_t n; int top = 0;
  pipe(fd);
  if (fork() == 0) {
    close(fd[1]);
    while ((n = read(fd[0], buf, 4)) > 0) {
      top += n;
      printf("%zd ", n);
    }
    printf("| %d\n", top);
    return 0;
  }
  close(fd[0]);
  write(fd[1], "hello world", 11);
  close(fd[1]);
  wait(NULL);
  return 0;
}

Multiple Choice · Interprocess Communication

Question 14: A Zero-Capacity Link

In message passing the link has zero buffer capacity; send and receive are blocking. If the producer calls send(m) before the consumer has called receive, what happens?

B: With zero capacity there is no place to store the message; the sender blocks until the receiver is ready, and the transfer happens when the two processes meet (rendezvous). A describes a bounded or unbounded buffer. With a rendezvous the producer cannot send a new message before the consumer has received the last one, so the two are synchronized automatically.

Multiple Choice · Mobile Systems

Question 15: The Background App

On iOS, an ordinary app that plays no audio and uses no location is moved to the background. What happens shortly afterwards?

A: In the background iOS keeps running only permitted work (audio, location, VoIP, scheduled tasks); other apps are suspended and terminated under memory pressure. The reason is limited memory and battery. Since version 8, Android also restricts long background work to foreground services or WorkManager.

The End

Chapter 3: Processes: Study Questions
Lecture slides: Chapter 3: Processes · Lecture notes
1 / 1 Sercan KÜLCÜ. All rights reserved.