我想创建一个服务器 - 客户端程序,其中两个进程使用共享内存在彼此之间传递信息
要传递的信息:
typedef struct shared_mem{
int board[BOARD_SIZE * BOARD_SIZE];
int goal;
}shared_mem;
shared_mem *msg;
服务器:
int main(int argc, char **argv) {
int shmid;
key_t key=ftok("2048_client", 42);
if(key == -1) {
printf("ftok failed");
return -1;
}
shared_mem *shm;
msg=(shared_mem *)malloc(sizeof(shared_mem));
/*
* Create the segment
*/
if ((shmid = shmget(key, sizeof(msg), IPC_CREAT)) < 0) {
perror("shmget");
exit(1);
}
/*
* Now we attach the segment to our data space.
*/
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
perror("shmat");
exit(1);
}
msg=shm;
(*msg).goal=64;
}
客户端:
int main(int argc, char **argv) {
int shmid;
key_t key=ftok("2048_client", 42);
if(key == -1) {
printf("ftok failed");
return -1;
}
shared_mem *shm;
msg=(shared_mem *)malloc(sizeof(shared_mem));
/*
* Create the segment.
*/
if ((shmid = shmget(key, sizeof(msg), 0)) < 0) {
perror("shmget");
exit(1);
}
/*
* Now we attach the segment to our data space.
*/
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
perror("shmat");
exit(1);
}
msg=shm;
printf("dscsadc: %d",msg->goal);
}
我是共享记忆的新手,我想了解它为什么不起作用以及它应该如何工作。我得到&#34; shmat:权限被拒绝&#34;
答案 0 :(得分:2)
问题是您使用0000权限创建共享内存段,因此没有人可以读取或写入它。
更改shmget()
来自:
if ((shmid = shmget(key, sizeof(msg), IPC_CREAT)) < 0) {
为:
if ((shmid = shmget(key, sizeof(msg), IPC_CREAT|0600)) < 0) {
只有运行程序的用户才能访问创建的共享内存。
请注意POSIX shmget()
表示:
shm_perm.mode
的低位9位设置为shmflg
的低位9位。
答案 1 :(得分:0)
如果您不仅限于C,请查看升级库。它使您能够为进程间通信创建共享内存段。
using boost::interprocess;
shared_memory_object shm_obj
(create_only, //only create
"shared_memory", //name
read_write //read-write mode
);
http://www.boost.org/doc/libs/1_54_0/doc/html/interprocess/sharedmemorybetweenprocesses.html
除此之外,您可以随时使用管道,或者如果您正在考虑使用Windows - COM。