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;
}