fork();

僵死進程: 父進程沒有等待子進程,wait() 子進程會變成僵死進程。函數

int main(int arg, char *args[])
{
 
  pid_t pid = fork();//調用fork產生一個子進行
  int status;
  if (pid == -1)
  {
  printf("fork failed\n");
  return 0;
  }
  if (pid == 0)//子進程調用execve,執行ls -l命令
  {
          exit(0);//子進程退出了,變成了僵死進程。進程

  }
  else
  {it

          printf("father exit");im

           //wait(&status);//阻塞調用,直到子進程退出,wait才返回異常

          sleep(10);//沒有等待子進程狀態。文件

     return 0;//父進程退出
  }
}co

孤兒進程: 父進程退出子進程尚未退出,會由init進程接管變成孤兒進程。阻塞

int main(int arg, char *args[])
{
  close(STDOUT_FILENO);//關閉標準輸出
  open("/dev/pts/2", O_WRONLY);//打開"/dev/pts/2",作爲標準輸出
  pid_t pid = fork();//調用fork產生一個子進行
  int status;
  if (pid == -1)
  {
  printf("fork failed\n");
  return 0;
  }
  if (pid == 0)//子進程調用execve,執行ls -l命令
  {
  char *args[] = { "/bin/ls", "-l", NULL };
  execve("/bin/ls", args, NULL);fork

  }
  else
  {生成

  return 0;//父進程退出
  }
}


//父進程等待子進程退出的代碼
int main(int arg, char *args[])
{
  pid_t pid = fork();//調用fork以後會有兩個進程
  int status;
  if (pid == 0)
  {
    printf("child begin\n");
    sleep(5);
    printf("child end\n");
    return -1;
  }

  if (pid > 0)
  {
    printf("parent begin\n");
    wait(&status);//阻塞調用,直到子進程退出,wait才返回
    printf("child return = %d\n", WEXITSTATUS(status));
    printf("parent end\n");
  }

  return 0;
}

//僵死進程
//父進程沒有調用wait,子進程就退出了,這個時候子進程就成了僵死進程

 

進程退出的5種方式:

return 跟exit 在主函數main中效果是同樣的,只是在子函數中,纔有區別,子函數中return只是退出子函數,exit纔是退出進程。

exit  在main函數中跟return是同樣的,只是在子函數中不相同。

_exit

abort  異常退出。生成一個core.xxx文件  (ulimit -c unlimited)  

信號  kill(pid , SIGKILL);

相關文章
相關標籤/搜索