1

I made a multi threaded server, it has a global pointer to a linked list, in thread I am trying to insert some data, but that data (which I insert) not retaining, is that possible that in threads that global value is not retaining. I am using the following code (it's a simplest version.)

struct node {
  int cn; //

  struct node *next;
};




/*GLOBAL VARIABLES*/
struct node *start; //Global pointer to Linked List
/* END */

int main(int argc, char *argv[]) {

    start = (struct node *)malloc(sizeof(struct node));
    start -> cn =0;

    int pid;
    /* Declaration of Server goes here */
    printf("Server Running ...\n");
    while (1) {

        /* accepting socket*/

        pid = fork();
        if (pid < 0)
            error("ERROR on fork");
        if (pid == 0)  {
            close(serverSocket);
            dostuff(childSocket,start);
            exit(0);
        }
        else
            close(childSocket);

    }
    return 0;
}

void dostuff (int sock, struct node *pointer){

    returnStatus = read(sock, &requestToJoin, sizeof(int));
    if (returnStatus < 0) 
        error("ERROR reading from socket");
    else{
        /* Insert Data to global Pointer */
    }

}
Muaz Usmani
  • 1,298
  • 6
  • 26
  • 48

3 Answers3

3

That's a multi-process server not multi-threaded, global data is not shared between parent and child processes it gets duplicated at a certain point, you should look into shared memory if you want to share data between multiple processes or pthreads if you want to use threads (which share their parent's memory). If your compiler supports C11 you could also use <threads.h>

iabdalkader
  • 17,009
  • 4
  • 47
  • 74
3

What you are using is multi-process and not multi-threading.

Threads share global memory (ie. global variables) but processes do not share memory (unless you setup shared memory) and each has its own set of global variables.

Iftah
  • 9,512
  • 2
  • 33
  • 45
2

You are using fork(). It creates a process that is a exactly copy of your actual process, but it don't share the same memory. If you use threads all the memory addressing is going to be shared and you need to synchronized the access to the shared memory position in order to satisfy the data's consistency.

Afaria
  • 403
  • 5
  • 14