0

Im having troubles on figuring out how can I use a list I created between different processes. What I have is:

FileList.h - The list I created

#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[]);

And in the FileList.cpp I create

FileList fl;

And implement the prototyped functions.

I will simplify my 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();
         }
    }
}

Why is this list not global once it is included as a header, therefore for father and children process, and how can I make it global?

4

1 回答 1

0

The process created by fork is a process and is not a thread. so you are talking about sharing list between process and not shared it between threads.

Sharing list between process directly is impossible. You have to use shared memory between proceess. You can use for example mmap

Example of how to use shared memory between process from How to share memory between process fork()? :

You can use shared memory (shm_open(), shm_unlink(), mmap(), etc.).

#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;
}
于 2013-04-01T13:14:05.817 回答