how to use shared memory to communicate between two processes

前端 未结 3 726
面向向阳花
面向向阳花 2020-12-14 04:14

I am trying to communicate between two processes. I am trying to save data(like name, phone number, address) to shared memory in one process and trying to print that data th

3条回答
  •  猫巷女王i
    2020-12-14 04:34

    char* shared_memory[3];
    ...
    shared_memory[3] = (char*) shmat (segment_id, 0, 0);
    

    You declare shared_memory as an array capable of holding three pointers to char, but what you actually do with it is to write a pointer one place behind the end of the array. Since there is no telling what the memory there is otherwise used for, what happens next is generally unpredictable.

    Things go conclusively bad afterwards when you try to make use of the pointers in shared_memory[0] through shared_memory[2], because those pointers have never been initialized. They are filled with meaningless garbage from the stack -- thus the segmentation fault.

    It seems, in general, that you're failing to distinguish between the array and its elements. You should go and make yourself a lot more comfortable with arrays and pointers in sequential code before you try your hand at shared-memory IPC.

    Note that shared memory is one of the more easy-to-get-wrong ways of doing IPC out there. Unless you have rigid efficiency constraints and are going to exchange a lot of data, it's much easier to work with pipes, named pipes, or sockets.

提交回复
热议问题