1.server端
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <semaphore.h>
#include <string.h>
int main(int argc,char **argv)
{
int shm_id;
char *ptr;
sem_t *sem;
char *data;
if (argc!=2)
{
printf("usage:shm_open<pathname>\n");
return -1;
}
shm_id=shm_open(argv[1],O_RDWR|O_CREAT,0644);/*第一步:创建共享内存区*/
if (shm_id==-1)
{
printf( "open shared memory error.errno=%d,desc=%s.\n", errno, strerror(errno));
return -1;
}
ftruncate(shm_id,100);/*第二步:调整共享内存区大小,shm_id为shm_open的返回值*/
sem=sem_open(argv[1],O_CREAT,0644,0);/*创建信号量*/
if (sem==SEM_FAILED)
{
printf( "open semaphore error.errno=%d,desc=%s.\n", errno, strerror(errno));
return -1;
}
ptr=mmap(NULL,100,PROT_READ|PROT_WRITE,MAP_SHARED,shm_id,0);/*第三步:连接共享内存区*/
strcpy(ptr,"\0");/*清空共享内存区*/
while(1)
{
sem_wait(sem);/*第四步:申请信号量*/
printf("server : %s\n",ptr);/*共享内存区内容*/
if(!strcmp(ptr,"close"))
{
printf("server out\n");
break;
}
}
sem_unlink(argv[1]);/*第五步:删除信号量*/
shm_unlink(argv[1]);/*第六步:删除共享内存区*/
return 0;
}
2.client端
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <semaphore.h>
#include <string.h>
#include <errno.h>
int main(int argc,char **argv)
{
int shm_id;
char *ptr;
sem_t *sem;
if (argc!=2)
{
printf("usage:shm_open <pathname>\n");
return -1;
}
shm_id=shm_open(argv[1],O_RDWR,0);/*第一步:打开共享内存区*/
if (shm_id==-1)
{
printf( "open shared memory error.errno=%d,desc=%s.\n", errno, strerror(errno));
return -1;
}
else
{
printf( "open shared memory ok.\n");
}
sem=sem_open(argv[1],0);/*打开信号量*/
if (sem==SEM_FAILED)
{
printf( "open semaphore error.errno=%d,desc=%s.\n", errno, strerror(errno));
return -1;
}
else
{
printf( "open semaphore ok.\n");
}
ptr=mmap(NULL,100,PROT_READ|PROT_WRITE,MAP_SHARED,shm_id,0);/*连接共享内存区*/
while(1)
{
fgets(ptr,20,stdin);/*从键盘读入数据到共享内存区*/
ptr[strcspn(ptr,"\n")]=0;
printf("client : %s\n",ptr);
sem_post(sem);/*释放信号量*/
if(!strcmp(ptr,"close"))
{
printf("out\n");
break;
}
}
return 0;
}
3.编译
gcc -o server shm_server_demo.c -lrt -lpthread