0
我有一个创建一些共享的内存空间,并提出的“Hello World”,在它&是应该看看这个共享内存空间,并打印出的“Hello World”控制台客户端的服务器因此,然而,而不是我只是得到一个“*”字符作为&它应该是服务器没有终止。下面是代码,任何见解,我怎么能解决这个问题表示赞赏。意外输出共享内存方案
server.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;
}