Linux 共享内存通信实验

【 实验目的】 】
1、掌握共享内存的创建和读写方式
2、熟悉 UNIX/LINUX 支持的共享内存通信方式
【 【 实验内容】 】
reader 和 writer 两个进程通过共享内存交换数据。writer 从标准输入读入字符串写入共享内存,reader
把共享内存里的字符串打印到标准输出。
reader 和 writer 通过信号实现同步
思路:
1. reader 和 writer 通过信号通信必须获取对方的进程号,可利用共享内存保存双方的进程号
2. reader 和 writer 运行的顺序不确定,可约定先运行的进程创建共享内存并初始化。
pid buf
<参考程序>
Reader.c

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <sys/ipc.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#define N 64
typedef struct
{
int pid;
char buf[N];
} shmbuf;
void handler(int signo)
{
return;
}
int main(int argc, char *argv[])
{
int shmid;
key_t key;
pid_t pid;
shmbuf *shmaddr;
signal(SIGUSR1, handler);
if ((key = ftok(".", 'a')) < 0)
{
perror("fail to ftok");
exit(-1);
}
if((shmid = shmget(key, sizeof(shmbuf), IPC_CREAT|IPC_EXCL|0666)) < 0)
{
if (errno == EEXIST)
{
shmid = shmget(key, sizeof(shmbuf), 0666);
shmaddr = (shmbuf *)shmat(shmid, NULL, 0);
pid = shmaddr->pid;
shmaddr->pid = getpid();
kill(pid, SIGUSR1);
}
else
{
perror("fail to shmget");
exit(-1);
}
}
else
{
shmaddr = (shmbuf *)shmat(shmid, NULL, 0);
shmaddr->pid = getpid();
pause();
pid = shmaddr->pid;
}
while ( 1 )
{
pause();
if ( strncmp(shmaddr->buf, "quit", 4) == 0)
{
break;
};
printf("message from shm : %s", shmaddr->buf);
usleep(100000);
kill(pid, SIGUSR1);
}
Linux 系统实验手册
3
shmdt(shmaddr);
return 0;
}

Write.c

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <sys/ipc.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#define N 64
typedef struct
{
int pid;
char buf[N];
} shmbuf;
void handler(int signo)
{
return;
}
int main(int argc, char *argv[])
{
int shmid;
key_t key;
pid_t pid;
shmbuf *shmaddr;
signal(SIGUSR1, handler);
if ((key = ftok(".", 'a')) < 0)
{
perror("fail to ftok");
exit(-1);
}
if((shmid = shmget(key, sizeof(shmbuf), IPC_CREAT|IPC_EXCL|0666)) < 0)
{
if (errno == EEXIST)
{
shmid = shmget(key, sizeof(shmbuf), 0666);
shmaddr = (shmbuf *)shmat(shmid, NULL, 0);
pid = shmaddr->pid;
shmaddr->pid = getpid();
kill(pid, SIGUSR1);
}
else
{
perror("fail to shmget");
exit(-1);
}
}
else
{
shmaddr = (shmbuf *)shmat(shmid, NULL, 0);
shmaddr->pid = getpid();
pause();
pid = shmaddr->pid;
}
while ( 1 )
{
printf("please input : ");
fgets(shmaddr->buf, N, stdin);
kill(pid, SIGUSR1);
if (strncmp(shmaddr->buf, "quit", 4) == 0)
{
break;
}
pause();
}
sleep(1);
shmdt(shmaddr);
shmctl(shmid, IPC_RMID, NULL);
return 0;
}

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

STM32单片机定制

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值