|
回复 7# 抗坏血酸
呃,其实我对共享内存也不太熟,翻了下《Linux程序设计》之后,将你的程序改动如下就可以通过了。
主要问题是你使用了共享内存,但是没有利用别的机制进行同步,使得mysem没有等待myinput放入数据就直接输出。
这里我就按书上写的用了一个struct来进行同步了。
再多的你可以自己看看《Linux程序设计》里面关于共享内存的部分。
myinput.c:- #include<stdlib.h>
- #include<stdio.h>
- #include<string.h>
- #include<linux/shm.h>
- #include<unistd.h>
- #include<sys/types.h>
- typedef struct shared_use_st {
- int written_by_you;
- char buffer[512];
- } Shared_use_st;
- main()
- {
- int myshm;
- void *viraddr;
- Shared_use_st *shared_mem;
- char buffer[512];
- myshm=shmget(1234,sizeof(Shared_use_st),0666|IPC_CREAT);//创建或获取共享内存id
- viraddr = shmat(myshm,(void*)0,0);//附接到共享内存
- shared_mem = (Shared_use_st*) viraddr;
- shared_mem->written_by_you = 0;
- while(1){
- if (shared_mem->written_by_you == 0)
- {
- printf("please input your chares:\n");
- fgets(buffer,512,stdin);
- strcpy(shared_mem->buffer,buffer);
- if(strncmp(shared_mem->buffer,"end",3)==0)
- break;
- shared_mem->written_by_you = 1;
- }
- else
- {
- sleep(1);
- }
- }
- shmdt(viraddr);//切断与共享内存的连接
- }
复制代码 mysem.c:- #include<stdlib.h>
- #include<stdio.h>
- #include<string.h>
- #include<linux/shm.h>
- #include<unistd.h>
- #include<sys/types.h>
- typedef struct shared_use_st {
- int written_by_you;
- char buffer[512];
- } Shared_use_st;
- main()
- {
- int myshm;
- void *viraddr;
- Shared_use_st *shared_mem;
- myshm = shmget(1234,sizeof(Shared_use_st),0666|IPC_CREAT);//创建或获取共享内存id
- if (myshm == -1)
- {
- fprintf(stderr, "shmget failed.\n");
- exit(1);
- }
- viraddr = shmat(myshm,(void*)0,0);//附接到共享内存
- shared_mem = (Shared_use_st*) viraddr;
- while (shared_mem->written_by_you == 0)
- {
- sleep(1);
- printf("waiting for data...\n");
- }
- printf("the message is:\n%s",shared_mem->buffer);
- shared_mem->written_by_you = 0;
- sleep(10);
- shmdt(viraddr);//切断与共享内存的连接
- shmctl(myshm,IPC_RMID,0);//撤销共享内存
- exit(0);
- }
复制代码 |
|