rcore-os / rCore-Tutorial-Book-v3

A book about how to write OS kernels in Rust easily.
https://rcore-os.github.io/rCore-Tutorial-Book-v3/
GNU General Public License v3.0
1.13k stars 211 forks source link

fix ch5's answer error #147

Closed kkocdko closed 1 year ago

kkocdko commented 1 year ago
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>

int main() {
  setbuffer(stdout, NULL, 0); // disable the output buffer
  int val = 2;
  printf("%d", 0);
  int pid = fork();
  if (pid == 0) {
    // sleep(1);
    val++;
    printf("%d", val);
  } else {
    // sleep(1);
    val--;
    printf("%d", val);
    wait(NULL);
  }
  val++;
  printf("%d", val);
  return 0;
}

Parent first:

[main  :09] > 0
[main  :17] > 1
[main  :18] wait until child return
[child :13] > 3
[child :21] > 4
[child :22] child exit
[main  :21] > 2

Child first:

[main  :09] > 0
[child :13] > 3
[child :21] > 4
[child :22] child exit
[main  :17] > 1
[main  :18] wait until child return
[main  :21] > 2

Uncomment the sleep(1) statements to simulate each case.