2017-03-14 47 views
0

我有一個函數,說pfoo(),我想通過調用fork來創建一個子進程。這個函數被重複調用很多次,但我希望只在第一次調用該函數時創建子進程。fork()函數裏面只有第一次調用的函數

有沒有可能做到這一點? 我應該如何更改下面的函數以確保fork()僅在第一次被調用?我需要緩存cpid嗎?

void pfoo() 
{ 
    pid_t cpid = fork(); 
    if (cpid == 0) 
    { 
     // child process 
    } 
    else 
    { 
     // parent process 
    } 
    .... 
    .... 
} 
+1

'static int forked = 0; if(!forked){...}' – StoryTeller

+0

'static pid_t cpid = 0;如果(cpid == 0){...}' – ikegami

+0

@ikegami - 我想到了,但如果OP想要在子進程中阻止它分叉呢? – StoryTeller

回答

2

static變量保持其呼叫呼叫的價值。

int calc(int n) { 
    static pid_t pid = 0; 
    static int request_pipe_fd; 
    static int response_pipe_fd; 

    if (pid == 0) { 
     ... create the worker ... 
    } 

    ... 
} 

您還可以使用文件範圍的變量。

static pid_t calc_worker_pid = 0; 
static int calc_worker_request_pipe_fd; 
static int calc_worker_response_pipe_fd; 

void launch_calc_worker() { 
    if (calc_worker_pid != 0) 
     return; 

    ... create the worker ... 
} 

void terminate_calc_worker() { 
    if (calc_worker_pid == 0) 
     return; 

    ... terminate and reap the worker ... 

    calc_worker_pid = 0; 
} 

int calc(int n) { 
    launch_calc_worker(); 

    ... 
}