Home > other >  Sending int through shared memory between two processes
Sending int through shared memory between two processes

Time:05-17

I would like to send an int from one process to another through shared memory.

I tried simply placing the value of the int into the shared memory (&number) - didnt work.

I tired casting the string to bytes into a char array (memcpy) and reading a sizeof(int) from the other process - didn't work.

i tired memcpy the value of the int into a char array, sending it to the other process, copying back it with memcpy : from the char array into an int - didn't work

My last attempt is this:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/shm.h>
#include <sys/stat.h> // S_IRUSR

int main(int argc, char *argv[])
{
    pid_t gyerek;
    key_t kulcs;
    int oszt_mem_id;
    char *s;

    kulcs = ftok(argv[0], 1);
    oszt_mem_id = shmget(kulcs, 500, IPC_CREAT | S_IRUSR | S_IWUSR);

    s = shmat(oszt_mem_id, NULL, 0);

    gyerek = fork();

    if (gyerek == 0)
    {

        //printf("Child read this: %s\n", s);

        char szamarr[10];
        int szam = 12; 
        memcpy(&szamarr, &szam, sizeof(int)); 
        strcpy(s, szamarr);

        sleep(1);

        strcpy(s, &szam);
        
        sleep(3);
        shmdt(s);
    }
    else
    {
        sleep(2);
        int szam;
        char szamarr[10];
        memcpy(&szamarr, &s, sizeof(int));

        printf("Parent read this: %s\n", szamarr);

        sleep(1);

        int szam2 = (int) s;

        printf("Parent read this: %s\n", s);

        shmdt(s);

        wait(NULL);
        shmctl(oszt_mem_id, IPC_RMID, NULL);
    }
}

The result is either a random number and nothing

CodePudding user response:

You don't need to involve strings if you only want to pass an int. However generally, it's easier to use structures for this kind of communication:

typedef struct {
    int szam;
    // ...
} mystruct_t;


int main(int argc, char *argv[])
{
    pid_t gyerek;
    key_t kulcs;
    int oszt_mem_id;
    char *s;

    kulcs = ftok(argv[0], 1);
    oszt_mem_id = shmget(kulcs, sizeof(mystruct_t), IPC_CREAT | S_IRUSR | S_IWUSR);

    s = shmat(oszt_mem_id, NULL, 0);

    gyerek = fork();

    if (gyerek == 0)    // child
    {
        mystruct_t ms={0};
        ms.szam = 12;
        memcpy(s, &ms, sizeof(mystruct_t));
        sleep(3);
        shmdt(s);
    }
    else    // parent
    {
        sleep(1);
        mystruct_t ms={0};
        memcpy(&ms, s, sizeof(mystruct_t));
        printf("Parent read this: %d\n", ms.szam);
        shmdt(s);
        wait(NULL);
        shmctl(oszt_mem_id, IPC_RMID, NULL);
    }
}
  • Related