发送端
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <semaphore.h>
int main()
{
char* shmaddr;
int shmgetId;
shmgetId = shmget(100, 4096, IPC_CREAT | 0666);
if(shmgetId == -1)
{
printf("shmget fail!\n");
exit(-1);
}
printf("shmget success!\n");
shmaddr = (char*)shmat(shmgetId, 0, 0);
printf("shmat success!\n");
sem_t* semr = sem_open("mysem_r", O_CREAT | O_RDWR, 0666, 1);
if(semr == SEM_FAILED)
{
printf("sem_r open fail!\n");
exit(-1);
}
sem_t* semw = sem_open("mysem_w", O_CREAT | O_RDWR, 0666, 1);
if(semw == SEM_FAILED)
{
printf("sem_w open fail!\n");
exit(-1);
}
while(1)
{
sem_wait(semw);
printf(">");
fgets(shmaddr, 1024, stdin);
sem_post(semr);
if(strncmp(shmaddr, "exit", 4) == 0)
{
break;
}
}
shmdt(shmaddr);
shmctl(shmgetId, IPC_RMID, 0);
return 0;
}
接收端
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <semaphore.h>
#include <unistd.h>
#include <fcntl.h>
int main()
{
char* shmaddr;
int shmgetId;
shmgetId = shmget(100, 4096, 0);
if(shmgetId == -1)
{
printf("shmget fail! \n");
exit(-1);
}
printf("shmget success!\n");
shmaddr = (char*)shmat(shmgetId, 0, 0);
printf("shmat success!");
sem_t* semr = sem_open("mysem_r", O_CREAT | O_RDWR, 0666, 1);
if(semr == SEM_FAILED)
{
printf("sem_r open fail!\n");
exit(-1);
}
sem_t* semw = sem_open("mysem_w", O_CREAT | O_RDWR, 0666, 1);
if(semw == SEM_FAILED)
{
printf("sem_w open fail!\n");
exit(-1);
}
while (1)
{
sem_wait(semr);// 阻塞等待读信号量的值为1后,减1返回
printf("%s\n", shmaddr);
sem_post(semw); // 读完之后设置写信号量,加1返回
if(strncmp(shmaddr, "exit", 4) == 0)
{
break;
}
}
shmdt(shmaddr);
return 0;
}
该代码示例展示了如何在C语言中通过shmget创建共享内存,sem_open创建信号量,实现发送端与接收端之间的数据传输。发送端读取用户输入并存储到共享内存,接收端则从共享内存读取数据并打印,直到接收到exit为止。整个过程利用信号量进行同步,确保读写操作的互斥。

被折叠的 条评论
为什么被折叠?



