我有一个服务器,可以创建一些共享内存空间并放置" 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;
}
答案 0 :(得分:0)
我已在使用gcc版本
运行的opensuse 42.1框之一上尝试过您的程序gcc版本4.8.5(SUSE Linux)以下是输出。你的程序很好,并按预期输出。请遵循以下详细信息。
/WorkDir/checks/stackover> gcc -Wall -Wextra -O2 -o unx_sh_server unx_sh_server.c
unx_sh_server.c: In function ‘main’:
unx_sh_server.c:12:14: warning: unused parameter ‘argc’ [-Wunused-parameter]
int main(int argc, char *argv[])
^
unx_sh_server.c:12:26: warning: unused parameter ‘argv’ [-Wunused-parameter]
int main(int argc, char *argv[])
^
/WorkDir/checks/stackover> gcc -Wall -Wextra -O2 -o unx_sh_client unx_sh_client.c
unx_sh_client.c: In function ‘main’:
unx_sh_client.c:11:14: warning: unused parameter ‘argc’ [-Wunused-parameter]
int main(int argc, char *argv[])
^
unx_sh_client.c:11:26: warning: unused parameter ‘argv’ [-Wunused-parameter]
int main(int argc, char *argv[])
/WorkDir/checks/stackover> ls -rlt
total 40
-rw-r--r-- 1 progra users 761 Feb 15 09:29 unx_sh_server.c
-rw-r--r-- 1 progra users 643 Feb 15 09:29 unx_sh_client.c
-rwxr-xr-x 1 progra users 12768 Feb 15 09:30 unx_sh_server
-rwxr-xr-x 1 progra users 12664 Feb 15 09:30 unx_sh_client
/WorkDir/checks/stackover> ./unx_sh_server &
[1] 12180
/WorkDir/checks/stackover>
/WorkDir/checks/stackover>
/WorkDir/checks/stackover> ./unx_sh_client
Hello World
/WorkDir/checks/stackover> fg
bash: fg: job has terminated`enter code here`
[1]+ Done ./unx_sh_server
/WorkDir/checks/stackover>
请检查您运行客户端和服务器的方式。