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