shmget for IPC in linux [closed]

喜欢而已 提交于 2019-12-14 03:31:08

问题


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



来源:https://stackoverflow.com/questions/26500476/shmget-for-ipc-in-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!