fork和殭屍進程

1. 關於fork

fork()函數: ios

   用於建立一個進程,所建立的進程複製父進程的代碼段/數據段/BSS段/堆/棧等全部用戶空間信息;在內核中操做系統從新爲其申請了一個PCB,並使用父進程的PCB進行初始化; less

#include <iostream>
#include <unistd.h>
using namespace std;
int val = 10;
int main(int argc, char *argv[])
{
    pid_t pid;
    int lval = 20;
​
    pid = fork();
​
    if(pid == 0){
        val += 2;
        lval += 5;
    }else{
        val -= 2;
        lval += 5;
    }
​
    if(pid == 0){
        cout << "val:" << val << ", lval = " << lval << endl;
    }else{
        cout << "val:" << val << ", lval = " << lval << endl;
    }
    return 0;
}

對於父進程而言,fork()函數返回子進程的ID(子進程的PID);而對於子進程而言,fork函數返回0。函數

殭屍進程

  父進程建立子進程後,子進程運行到終止時刻(例如,調用exit()函數,或者運行到main中的return語句時,都會將返回的值傳遞給 操做系統),此時若是父進程還在運行,子進程並不會當即被銷燬,直到這些值傳到了產生該子進程的父進程。也就是說,若是父進程沒有主動要求得到子進程的結束狀態值,操做系統就會一直保存該進程的相關信息,並讓子進程長時間處於殭屍狀態,例以下面程序:測試

int main(){
    pid_t pid = fork();
    if(pid == 0){
        cout << "I am a Child Process." <<endl;
    }else{
        cout << "I am a Father Process and Child Process is " << pid << endl;
        sleep(30);  //讓父進程休眠30秒,此時便於觀察子進程的狀態
    }
    if(pid == 0){
        cout << " Child Process exits " << endl;
    }else{
        cout << "Father Process exits " << endl;
    }
    return 0;
}

此時,運行該程序,查看後臺進程可知(test16是該測試程序的名稱,defunct表示殭屍進程):spa

gqx@gqx-Lenovo-Product:~$ ps -au
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root       923  0.6  0.9 480840 159824 tty7    Ssl+ 4月09  36:07 /usr/lib/xorg/
root      1351  0.0  0.0  17676  1768 tty1     Ss+  4月09   0:00 /sbin/agetty -
...
gqx      24856  0.0  0.0      0     0 pts/11   Z+   11:03   0:00 [tes16] <defunct>
gqx      24859  0.0  0.0  39104  3300 pts/3    R+   11:03   0:00 ps -au

殭屍進程的消除操作系統

方法一:調用wait()函數:code

/* Wait for a child to die.  When one does, put its status in *STAT_LOC
   and return its process ID.  For errors, return (pid_t) -1.
​
   This function is a cancellation point and therefore not marked with
   __THROW.  */
extern __pid_t wait (__WAIT_STATUS __stat_loc);

成功返回終止的進程ID,失敗返回-1;子進程的最終返回值將指向該函數參數所指向的內存空間,但函數所指向的內存單元總還含有其餘的信息,須要使用宏進行分離。blog

# define WIFEXITED(status)  __WIFEXITED (__WAIT_INT (status))  //子進程正常終止返回"true"
# define WEXITSTATUS(status)    __WEXITSTATUS (__WAIT_INT (status)) //返回子進程的返回值

要注意的是:若是沒有已終止的子進程,那麼程序將被阻塞,直到有子進程終止。進程

方法二:調用waitpid()函數內存

/* Wait for a child matching PID to die.
   If PID is greater than 0, match any process whose process ID is PID.
   If PID is (pid_t) -1, match any process.
   If PID is (pid_t) 0, match any process with the
   same process group as the current process.
   If PID is less than -1, match any process whose
   process group is the absolute value of PID.
   If the WNOHANG bit is set in OPTIONS, and that child
   is not already dead, return (pid_t) 0.  If successful,
   return PID and store the dead child's status in STAT_LOC.
   Return (pid_t) -1 for errors.  If the WUNTRACED bit is
   set in OPTIONS, return status for stopped children; otherwise don't.
​
   This function is a cancellation point and therefore not marked with
   __THROW.  */
extern __pid_t waitpid (__pid_t __pid, int *__stat_loc, int __options);

第一個參數:若是__pid的值是-1,則與wait()函數相同,能夠等待任意的子程序終止;若是是0,則等待進程組識別碼與目前進程相同的任何子進程;若是pid>0,則等待任何子進程識別碼爲 pid 的子進程。

第二個參數:與前一個函數wait()的參數意義相同。

第三個參數:經常使用WNOHANG——若pid指定的子進程沒有結束,則waitpid()函數返回0,不予以等待。若結束,則返回該子進程的ID。

示例程序以下:

#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
using namespace std;
​
void read_childproc(int sig){
    int status;
    pid_t id = waitpid(-1, &status, WNOHANG);
    if(WIFEXITED(status)){
        printf("Remove proc id: %d \n", id);
        printf("Child send: %d \n", WEXITSTATUS(status));
    }
}
​
int main(){
    pid_t pid;
    struct sigaction act;
    act.sa_handler = read_childproc;
    sigemptyset(&act.sa_mask);
    act.sa_flags = 0;
    sigaction(SIGCHLD, &act, 0);
​
    pid = fork();
​
    if(pid == 0){
        puts("Hi, I am a child process!");
        sleep(6);
        return 12;
    }else{
        printf("Child proc id: %d \n", pid);
        pid = fork();
        if(pid == 0){
            puts("Hi, I am a child process!");
            sleep(13);
            exit(24);
        }else{
            int i;
            printf("Child proc id: %d \n", pid);
            for(i  = 0; i < 4; i++){
                puts("wait...");
                sleep(5);
            }
        }
    }
    return 0;
}
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息