-1

I want to share variables between client-server program. I have server and 2 Clients. I made shm with shmget but I cant reat variables in client

Server:

if ((nMemID=shmget(kluc, sizeof(udaje[2]), IPC_CREAT|0777))==-1)
{
    perror("Nepodarilo sa vytvorit segment zdielanej pamate\n");
    exit(-100);
}

if ((shared =(udaje *)shmat(nMemID, NULL, 0))==NULL )
{
    fprintf(stderr,"Nepodarilo sa pripojit na rad sprav\n");
    exit(-1);
}
shared->hlavnaNadrz=50000;
shared->nadrz1=1200;

Client:

 if ((zdielanie =(udaje *)shmat(nMemID, NULL, 0))==NULL )
{
    fprintf(stderr,"Nepodarilo sa pripojit na rad sprav\n");
    exit(-1);
}
data=zdielanie->hlavnaNadrz;
Patrick
  • 21
  • 5
  • Can't read or can't attach? – HAL Dec 09 '13 at 15:45
  • can't read from sharedMemor. But in ipcs I have the sharedmemory created 0x0000162e 62619660 fitz 777 48 1 – Patrick Dec 09 '13 at 15:46
  • If your client and server programs are going to be communicating across a network then sharing memory between the processes isn't going to work. Since the memory is allocated on your server, and not your clients. – EdgeCaseBerg Dec 09 '13 at 15:47
  • What happens when you run this code? Describe anything particular about the environment too. Also, both client and server are on the same host, right? Sharing memory does not work across networks. – Guido Dec 09 '13 at 15:47
  • 1
    Watch out, shmat() returns -1 on failure rather than NULL. – Jeremy Friesner Dec 09 '13 at 15:48
  • server create shared memory and localhost server. My client connect to the server and I want to send data from shared memory back to server through socket. – Patrick Dec 09 '13 at 15:49

1 Answers1

1

Read the data in for loop:

    if (shmctl(shmid, SHM_LOCK, NULL) == -1)
    {
        printf ("Unable to lock the shared storage: Reason %s\n", strerror(errno));
        break;
    }
    ShrStruct = (struct SharedStruct *)shm;
    if (strlen(ShrStruct->Name) && ShrStruct->EmpID != 0)
    {
        printf("Data Received : Name --> %s || Employee ID --> %ld\n", ShrStruct->Name, ShrStruct->EmpID);
        memset(shm, '\0', sizeof(struct SharedStruct));
    }
    if (shmctl(shmid, SHM_UNLOCK, NULL) == -1)
    {
        printf ("Unable to unlock the shared storage: Reason %s\n", strerror(errno));
        break;
    }
Ankit Tripathi
  • 374
  • 1
  • 8
  • 1
    Its working now without unlock... I only add shmget to my client before shmat and it solved the problem. – Patrick Dec 09 '13 at 16:57