1. 共享内存实现两个进程实现通信,
要求:一个进程循环从终端输入,另一个进程循环打印,当输入quit时结束
这两个标志在两个进程里,是不共享的,所以为了共享标志位可以和buf封装到一个结构体里作为共享内存。
struct msg
{
int flag;
char buf[32];
};
两个进程通过同一个key值打开同一个·共享内存,然后对同一个共享内存进行读写
第一部分:
输入进程shmquitin,向共享内存中写入内容
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
typedef struct msg_node
{
int flag; // 标志位
char buf[32]; // 数组
} msg, *msg_t;
int main(int argc, char const *argv[])
{
// 创建key值
key_t key;
key = ftok("shmquitin.c", 'd');
if (key < 0)
{
perror("key error");
return -1;
}
printf("key:%#x\n", key);
// 创建或打开共享内存
// 不存在创建,存在返回-1
int shmid;
shmid = shmget(key, sizeof(msg), IPC_CREAT | IPC_EXCL | 0777);
if (shmid <= 0)
{
if (errno == EEXIST) // 如果存在,直接打开,返回id
{
shmid = shmget(key, sizeof(msg), 0777);
}
else
{
perror("shmid error");
return -1;
}
}
printf("shmid:%d\n", shmid);
// 映射共享内存
msg *p = NULL;
p = (msg *)shmat(shmid, NULL, 0);
if (p == (msg *)-1)
{
perror("shmat err");
return -1;
}
p->flag = 0;
// 操作共享内存
while (1)
{
// flag等于0时,进行输入
if (p->flag == 0)
{
scanf("%s", p->buf);
p->flag = 1;
}
if (strcmp(p->buf, "quit") == 0)
break;
}
// 取消映射
shmdt(p);
// 删除共享内存
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
第二部分:
输出进程,shmquitout,从共享内存中读取内容并输出到终端
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
typedef struct msg_node
{
int flag; // 标志位
char buf[32]; // 数组
} msg, *msg_t;
int main(int argc, char const *argv[])
{
msg *p = NULL;
// 创建key值
key_t key;
key = ftok("shmquitin.c", 'd');
if (key < 0)
{
perror("key error");
return -1;
}
printf("key:%#x\n", key);
// 创建或打开共享内存
// 不存在创建,存在返回-1
int shmid;
shmid = shmget(key, sizeof(msg), IPC_CREAT | IPC_EXCL | 0777);
// 如果存在,直接打开,返回id
if (shmid <= 0)
{
if (errno == EEXIST)
{
shmid = shmget(key, sizeof(msg), 0777);
}
else
{
perror("shmid error");
return -1;
}
}
printf("shmid:%d\n", shmid);
// 映射共享内存
p = (msg *)shmat(shmid, NULL, 0);
if (p == (msg *)-1)
{
perror("shmat err");
return -1;
}
// 操作共享内存
p->flag = 1;
// 操作共享内存
while (1)
{
// flag等于1时,进行输出
if (p->flag == 1)
{
printf("%s\n", p->buf);
p->flag = 0;
}
if (strcmp(p->buf, "quit") == 0)
break;
}
// 取消映射
shmdt(p);
// 删除共享内存
shmctl(shmid, IPC_RMID, NULL);
return 0;
}