Deadlock

Definition

Deadlock 只多個 process 互相在等待對方持有的資源,結果因為互等造成他們都無法繼續執行

在發生 deadlock 時,kernel 會以他超高的權限來干涉使 processes 可以擺脫 deadlock

Example

int main(void)
{
    int     var;        /* automatic variable on the stack */
    pid_t   pid;
 
    var = 88;
    printf("before vfork\n");  /* we don't flush stdio */
    if ((pid = vfork()) < 0) {
        err_sys("vfork error");
    } else if (pid == 0) {      /* child */
        while (var < 100 );      /* parent's variables */
        _exit(0);               /* child terminates */
    }
    /* Parent continues here. */
    var = 100;
    exit(0);
}
  • 可以看到 child process 要回傳 var 要大於等於 100
  • 但要讓 var 變成 100,需要 child process 先結束才能讓 parent process 執行 var=100
  • 結果造成這段程式碼永遠不能結束