gpt4 book ai didi

c - 仅在第一次调用函数时在函数内部进行 fork()

转载 作者:太空宇宙 更新时间:2023-11-04 08:06:10 25 4
gpt4 key购买 nike

我有一个函数,比如 pfoo(),我想通过调用 fork 在其中创建一个子进程。此函数被重复调用多次,但我希望仅在第一次调用该函数时创建子进程。

这有可能实现吗?我应该如何更改下面的函数以确保只在第一次调用 fork() ?我需要缓存 cpid 吗?

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

最佳答案

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();

...
}

关于c - 仅在第一次调用函数时在函数内部进行 fork(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42795798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com