2017-03-14 49 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(); 

    ... 
}