gpt4 book ai didi

c - Fork - 在 fork 进程之间共享列表

转载 作者:行者123 更新时间:2023-11-30 17:53:12 26 4
gpt4 key购买 nike

我在弄清楚如何使用在不同进程之间创建的列表时遇到了麻烦。我所拥有的是:

FileList.h - 我创建的列表

#include "Node.h"
typedef struct FileList {
struct Node *first;
struct Node *last;
int length;
} FileList;

void fl_initialize();
void fl_add(char name[], char up[], bool status);
void fl_edit(Node *n, char up[]);
void fl_remove (char name[]);
int fl_length();
void fl_clear();
void fl_print();
void fl_print_node(Node *n);
void fl_uncheck();
bool fl_clean_unchecked();
Node* fl_get(int pos);
Node* fl_find (char name[]);

在我创建的 FileList.cpp 中

FileList fl;

并实现原型(prototype)函数。

我将简化我的 main.cpp

#include "FileList.h"
int main (int argc, char *argv[]) {
int r = fork();
if (r == 0) {
fl_initialize();
call_function_that_add_list_elements();
fl_print(); //List contains elements
} else {
waitpid(r, &status, WUNTRACED | WCONTINUED);
if (WIFEXITED(status)) {
fl_print(); //The list is empty (Is other list, probably);
//another_function_that_should_keep_working_with_the_list();
}
}
}

为什么这个列表一旦作为标题包含在内就不是全局的,因此对于父亲和 child 的进程来说,我怎样才能使其全局?

最佳答案

fork创建的进程是进程,不是线程。所以你正在谈论在进程之间共享列表,而不是在线程之间共享它。

在进程之间直接共享列表是不可能的。您必须在进程之间使用共享内存。您可以使用例如 mmap

示例如何在 How to share memory between process fork()? 的进程之间使用共享内存:

您可以使用共享内存(shm_open()shm_unlink()mmap() 等)。

#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

static int *glob_var;

int main(void)
{
glob_var = mmap(NULL, sizeof *glob_var, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS, -1, 0);

*glob_var = 1;

if (fork() == 0) {
*glob_var = 5;
exit(EXIT_SUCCESS);
} else {
wait(NULL);
printf("%d\n", *glob_var);
munmap(glob_var, sizeof *glob_var);
}
return 0;
}

关于c - Fork - 在 fork 进程之间共享列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15744132/

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