linux進程編程

 

創建一個新進程
   1.可以使用system函數在程序裏創建一個新的進程,函數定義如下:
        int system (const char *string);
       string代表運行的命令。
  2.可以使用以exec開頭的一系列函數來開始一個新進程,這些函數有:
      int execl(const char *path, const char *arg0, ..., (char *)0);
       int execlp(const char *file, const char *arg0, ..., (char *)0);
       int execle(const char *path, const char *arg0, ..., (char *)0, char *constenvp[]);
       int execv(const char *path, char *const argv[]);
       int execvp(const char *file, char *const argv[]);
       int execve(const char *path, char *const argv[], char *const envp[]);
     這些函數分爲兩類。execl,execlp和execle使用可變數目的參數,最末尾的參數則是一個空指針。execv和execvp的第二個參數是一個字符串數組。兩種情況下,參數的值都是傳到新建的進程的main函數的argv參數裏。但最通常使用的是execve函數。
      
複製一個進程
      也是創建一個新進程,但是新的進程先複製當前的進程,在進程表裏獲得一個新的ID,新的進程與原有進程使用相同的代碼但有自己獨立的數據空間和文件描述符,函數定義如下:
      pid_t fork(void);
      父進程裏調用的fork函數返回的是子進程的PID,新的子進程按照父進程的代碼繼續往下執行,但在子進程裏fork函數的返回值是0。這樣子進程和父進程就得以區分。下面的例子演示瞭如何使用fork函數複製一個新進程:
運行結果可能如下:
$ ./fork1
fork program starting
This is the child
This is the parent
This is the parent
This is the child
This is the parent
This is the child
$ This is the child
This is the child
等待一個進程
有時候希望父進程與子進程的運行能夠同步,當父進程比子進程運行快時,父進程可以調用wait函數使該進程暫停直到子進程結束。該函數的定義如下:

       pid_t wait(int *stat_loc);

下面是該函數的使用示例,將以下代碼插入上面的程序。

首先添加一個變量定義:

 

在case 0裏添加代碼:

 

在case 1裏添加代碼:

 

在最後的exit前添加以下代碼:

運行結果可能如下:

$ ./wait

fork program starting

This is the child

This is the parent

This is the parent

This is the child

This is the parent

This is the child

This is the child

This is the child

Child has finished: PID = 1582

Child exited with code 37

 

 

殭屍進程

     當子進程先結束,而父進程還在運行時,子進程在進程表裏依然保存一個入口,但子進程本身已經不是活動的了,這種情況稱爲殭屍進程。

 

信號

     信號是linux系統裏對某些情況(如:產生錯誤)產生的事件,這樣的事件產生後可能引起某個進程的某個動作,信號能夠被髮送,捕捉,響應以及忽略。在signal.h包含了關於信號的函數和數據定義。如函數signal,定義如下:

 

void (*signal(int sig, void (*func)(int)))(int);

     參數sig表示發送的信號的類型,後面的函數指針表示進程接收到信號後將要執行的動作。關於signal的具體使用以及一些其它signal函數請參閱《Begining Linux Programming 4th edition》。

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章