2014年5月24日 星期六

Linux-C語言-fork()

這似乎要從這邊開始解釋


什麼是程序 (process)
在 Linux 系統當中:『觸發任何一個事件時,系統都會將他定義成為一個程序,並且給予這個程序一個 ID ,稱為 PID,同時依據啟發這個程序的使用者與相關屬性關係,給予這個 PID 一組有效的權限設定。』 從此以後,這個 PID 能夠在系統上面進行的動作,就與這個 PID 的權限有關了!


程序與程式 (process & program)
我們如何產生一個程序呢?其實很簡單啦,就是『執行一個程式或指令』就可以觸發一個事件而取得一個 PID 囉!我們說過,系統應該是僅認識 binary file 的,那麼當我們要讓系統工作的時候,當然就是需要啟動一個 binary file 囉,那個 binary file 就是程式 (program) 啦!

使用者 -------->(執行)磁碟中的程式----->(載入記憶體)

記憶體中程序產生的相關資料包含 PID+執行者的權限屬性參數+程式所需程式碼與相關資料. 這應該是由OS所管理和產生的

fork是UNIX一個系統呼叫(system call),process fork時,會複製一個跟自己完全一模一樣的process (with different pid),並利用系統呼叫完成之傳回值,來區分parent process 與child process,而分別賦予child process不同的功能



基本宣告:
    pid_t ford(void) // creat child process

    RETURN VALUE
    On success, the PID of the child process in returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately.
    果然還是英文解釋比較簡單明瞭,意思就是process執行成功之後,回傳的值的類型....
    1. 如果是child process執行成功,就回傳 0
    2. 如果是parent process執行成功,就回傳child process的PID
    3. 如果出現錯誤(大概是指有process執行錯誤或是產生child process失敗吧!),則回傳的值為 -1



Example: fork1.c

#include <unistd.h>   // 要宣告這個 header file,這樣 pid_t 才會被認得
#include <stdio.h>

main()
{
   pid_t pid_test;
   pid_test=fork();  // 執行完這行,就會產生出一個child process

   //這時就有parent process和child process同時在運行
   if (pid_test < 0)            //表示有錯誤發生
      printf("error in fork!");
   else if (pid_test == 0) // 表示child process執行成功
      printf("I am the child process, ID is %d\n", getpid());
   else                              // 表示parent process執行成功
      printf("I am the parent process, ID is %d\n", getppid());

}



執行結果:
>gcc fork1.c -o fork1
I am the parent process, ID is 3403
I am the child process, ID is 11571



Note:
  1. 這只是基本解釋,至於fork在linux中的真正作用為何,還需要找資料來了解和補充

參考資料:
1. 鳥哥的Linux私房菜
http://linux.vbird.org/linux_basic/0440processcontrol.php

沒有留言:

張貼留言