shmget for IPC in linux [closed]

2019-09-27 01:43发布

问题:

I'm really new to linux OS. Can someone say how to do this work with linux. I'm not asking the C code. It's hard to understand it. Thank you
1. First program creates a shared memory area using shmget() and maps it to its address space. Then it writes "Hello" in to that shared memory area. Then it waits until the first byte in the shared memory area becomes *.
2. The second program should be started after the first one. It maps the shared memory area created by the first program into its address space and reads the string and prints it to the terminal. Then it changes the first byte of the shared memory area to *.

回答1:

I think this is what you're looking for.

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

#define SHSIZE 100

int main(){

    int shmid;
    char *shm;

    shmid = shmget(9876, SHSIZE, IPC_CREAT | 0660);
    shm = shmat(shmid, NULL, 0);
    memcpy(shm, "Hello", 5);

    while(*shm != '*'){
    sleep(1);
    }

return 0;
}

And the client:

#include <stdio.h>
#include <sys/shm.h>

#define SHSIZE 100

int main(){
    int shmid;
    char *shm,*s;

    shmid = shmget(9876, SHSIZE, IPC_CREAT | 0660);
    shm = shmat(shmid, NULL, 0);

    for(s = shm; *s != 0; s++){
    printf("%c", *s);
    }
    printf("\n");

    *shm = '*';

return 0;
}


回答2:

So basically you're asking how to use shared memory to exchange data between two programs. This is another form of IPC, or Inter-process communication.

Refer to this link for a video tutorial!

https://www.youtube.com/watch?v=IFRbX8u6lB0