在C中分享孩子和父母之间的链表

时间:2015-07-16 09:18:19

标签: c fork shared-memory

我有一个链表。我有很多子进程在这个链表上工作,添加和删除元素。如何在所有孩子之间分享?

我尝试过使用内存映射的代码:

#include <stdio.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <err.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>

typedef struct Struttura
{
    int prova;
    struct Struttura* next;
} Struttura;

Struttura* glob;
int main()
{
    int fd = open("/dev/zero", O_RDWR, 0);
    glob = mmap(NULL, sizeof(Struttura), PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED, fd, 0);

    int pid = fork();
    if(pid == 0)
    {
        printf("Glob value: %d\n", glob->prova);
        glob->next = mmap(NULL, sizeof(Struttura), PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED, fd, 0);
        glob->next->prova = 3;
        printf("The next value: %d\n\n", glob->next->prova);
        return (0);
    }
    else
    {
        wait(NULL);
        printf("Glob value: %d\n", glob->prova);
        printf("The next value: %d\n\n", glob->next->prova); //Segmentation fault core dumped
    }
    return (0);
}

怎么做?请不要介意同步和未经检查的返回值,因为这只是一次尝试:)

2 个答案:

答案 0 :(得分:4)

使用mmap(2),您无法在不对列表的最大大小施加某些限制的情况下轻松完成此操作。原因是很容易分配一大块内存来与子进程共享,但是在分叉之后增加那些块是不可行的。

您可以通过使用XSI共享内存接口来解决这个问题(请参阅man 7 shm_overview):您使用shm_open(3)创建和访问共享内存块,您可以设置其大小与ftruncate(2)。从理论上讲,这将为您提供动态增长和缩小的能力,但代价是更复杂的代码:与mmaped内存不同,XSI共享内存对象在关闭之前不会从系统中删除,或者直到所有进程都取消映射对象并使用shm_unlink(3)将其删除。如果任何进程崩溃并异常终止,则会出现清理问题。此外,每次有人更改内存对象的大小时,您都面临着通知每个其他进程的问题。如果在插入过程中通知进程会怎么样?如果一个进程将一个节点插入一个不再存在的内存位置会怎么样,因为同时有人缩小了它的大小?

你并没有真正提到为什么要这样做,但在所有情况下,你最好使用线程。线程在这里是一个更加理智和合理的选择,因为它们正是为了这个目的:简单的资源共享。您不必设置共享内存段,并且列表的大小不限于您分配的块的大小。

无论如何,这是一个用mmap(2)创建共享内存段的程序示例,并且有一堆子进程在保存在该内存段中的链表中添加和删除元素。前几个内存块用于一些管家事务,即指向列表头和自由节点列表的指针,以及用于同步访问的互斥锁。我们需要保留一个空闲节点列表,以便在将新节点添加到真实列表时,工作进程可以找到空闲节点。每个工作进程(其中有10个)将10个新节点插入到存储工作进程ID的列表中。每次插入时,工作进程都会打印整个列表。插入所有这些节点后,工作进程将其从列表中删除并终止。

请注意,列表的最大大小为1024,因为这是我们分配的内容。

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

#define MAX_LIST_SZ 1024
#define WORKERS 10
#define WORK_UNIT 10

struct list_node {
    long value;
    struct list_node *next;
};

static struct list_node **list_head;
static struct list_node **free_head;
static pthread_mutex_t *mutex;

void print_list(void) {
    struct list_node *curr = *list_head;

    while (curr != NULL) {
        printf("%ld -> ", curr->value);
        curr = curr->next;
    }

    printf("NULL\n");
}

void do_work(void) {
    int i;
    for (i = 0; i < WORK_UNIT; i++) {
        pthread_mutex_lock(mutex);

        struct list_node *n = *free_head;

        if (n == NULL) {
            pthread_mutex_unlock(mutex);
            assert(0);
        }

        *free_head = (*free_head)->next;
        n->value = (long) getpid();
        n->next = *list_head;
        *list_head = n;

        print_list();

        pthread_mutex_unlock(mutex);
    }

    for (i = 0; i < WORK_UNIT; i++) {
        pthread_mutex_lock(mutex);
        struct list_node *n = *list_head;
        *list_head = (*list_head)->next;
        n->next = *free_head;
        *free_head = n;
        pthread_mutex_unlock(mutex);
    }

}

int main(void) {
    void *ptr;
    size_t region_sz = 0;

    /* Space for the nodes */
    region_sz += sizeof(**list_head)*MAX_LIST_SZ;

    /* Space for house-keeping pointers */
    region_sz += sizeof(list_head)+sizeof(free_head);

    /* Space for the mutex */
    region_sz += sizeof(*mutex);

    ptr = mmap(NULL, region_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
    if (ptr == MAP_FAILED) {
        perror("mmap(2) failed");
        exit(EXIT_FAILURE);
    }

    /* Set up everything */
    mutex = ptr;
    free_head = (struct list_node **) (((char *) ptr)+sizeof(*mutex));
    list_head = free_head+1;

    *free_head = (struct list_node *) (list_head+1);
    *list_head = NULL;

    /* Initialize free list */
    int i;
    struct list_node *curr;

    for (i = 0, curr = *free_head; i < MAX_LIST_SZ-1; i++, curr++) {
        curr->next = curr+1;
    }

    curr->next = NULL;

    pthread_mutexattr_t mutex_attr;
    if (pthread_mutexattr_init(&mutex_attr) < 0) {
        perror("Failed to initialize mutex attributes");
        exit(EXIT_FAILURE);
    }

    if (pthread_mutexattr_setpshared(&mutex_attr, PTHREAD_PROCESS_SHARED) < 0) {
        perror("Failed to change mutex attributes");
        exit(EXIT_FAILURE);
    }

    if (pthread_mutex_init(mutex, &mutex_attr) < 0) {
        perror("Failed to initialize mutex");
        exit(EXIT_FAILURE);
    }

    for (i = 0; i < WORKERS; i++) {
        pid_t pid;
        if ((pid = fork()) < 0) {
            perror("fork(2) error");
            exit(EXIT_FAILURE);
        }

        if (pid == 0) {
            do_work();
            return 0;
        }
    }

    for (i = 0; i < WORKERS; i++) {
        if (wait(NULL) < 0) {
            perror("wait(2) error");
        }
    }

    assert(*list_head == NULL);

    return 0;
}

答案 1 :(得分:0)

不要使用制表符进行缩进,因为每个编辑器/字处理器都有不同的制表符宽度/制表位

mmap()返回一个void *,它可以分配给任何指针,所以

1) do not cast the return value.
2) always check the returned value for MAP_FAILED which indicates the operation failed

调用fork()后的pid值被错误地使用

1) when pid <  0 then an error occurred
2) when pid == 0 then child executing
3) when pid >  0 then parent executing

使用fork()时,请始终检查所有三个条件

发布的代码错误地使用了pid值

建议阅读所使用的每个系统功能的手册页