【发布时间】:2017-02-15 03:02:49
【问题描述】:
我有一个服务器,它创建一些共享内存空间并将“hello world”放入其中,一个客户端应该查看该共享内存空间并相应地将“hello world”打印到控制台;但是,相反,我只是得到一个“*”字符,并且服务器没有按预期终止。以下是代码,感谢您对如何解决此问题的任何见解。
服务器.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SHSIZE 100
int main(int argc, char *argv[])
{
int shmid;
key_t key;
char *shm;
char *s;
key = 9876;
shmid = shmget(key, SHSIZE, IPC_CREAT | 0666);
if (shmid < 0)
{
perror("shmget");
exit(1);
}
shm = shmat(shmid, NULL, 0);
if (shm == (char *) -1)
{
perror("shmat");
exit(1);
}
memcpy(shm, "Hello World", 11);
s = shm;
s += 11;
*s = 0;
while (*shm != '*')
{
sleep(1);
}
shmdt (shm); // detach
shmctl (shmid, IPC_RMID, 0); //deallocate
return 0;
}
client.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SHSIZE 100
int main(int argc, char *argv[])
{
int shmid;
key_t key;
char *shm;
char *s;
key = 9876;
shmid = shmget(key, SHSIZE, IPC_CREAT | 0666);
if (shmid < 0)
{
perror("shmget");
exit(1);
}
shm = shmat(shmid, NULL, 0);
if (shm == (char *) -1)
{
perror("shmat");
exit(1);
}
for (s = shm; *s != 0; s++)
{
printf("%c", *s);
}
printf("\n");
*shm = '*';
return 0;
}
【问题讨论】:
标签: c server client output shared-memory