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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
João Menighin
  • 3,083
  • 6
  • 38
  • 80
  • http://stackoverflow.com/questions/9961591/sharing-heap-memory-with-fork should help you to understand how to share heap between forked processes – Roman Saveljev Apr 01 '13 at 13:15

1 Answers1

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;
}
Community
  • 1
  • 1
MOHAMED
  • 41,599
  • 58
  • 163
  • 268
  • Humm... It's way more complicated than I thought... I will try it asap, thanks for the quick reply – João Menighin Apr 01 '13 at 13:25
  • @JoãoMenighin I know that: you have to use other solution like threads. with threads you can share list without problems. Any way you are welcome – MOHAMED Apr 01 '13 at 13:27