实验八 进程间的通信
实验八 进程间通信
| 项目 | 内容 |
|---|---|
| 作业位于哪 | 班级地址 |
| 作业要求在哪 | 作业要求 |
| 学号-姓名 | 17041522-谢卢平 |
| 作业学习目标 | 1. 了解进程间通信的常用方式; 2. 掌握管道、消息队列、信号量、共享内存实现进程间通信的方法。 |
1、管道通信
匿名管道
例题:父进程 fork 出一个子进程,通过无名管道向子进程发送字符,子进程收到数据后将字符串中的小写字符转换成大写并输出。
程序:
/*************************************************************************
> File Name: hellopipe.c
> Author: xieluping
> Mail: 2234717859@qq.com
> Created Time: 2020年05月25日 星期一 19时23分19秒
************************************************************************/
#include<stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <ctype.h>
void child(int *fd) {
close(fd[1]); // 子进程关闭写端
char buf[64];
int n = 0,i;
while(1) {
n = read(fd[0], buf, 64);//如果没有数据可读,read会阻塞;如果父进程退出, read 返回 0.
for (i = 0; i < n; ++i)
putchar(toupper(buf[i]));
if (*buf == 'q') {
close(fd[0]);
exit(0);
}
if (n == 0) {
puts("no data to read!");
sleep(1);
}
}
xit(0);
}
int main() {
int fd[2];//作为传出参数
int n = 0;
char buf[64] = { 0 };
if (pipe(fd) < 0) {
perror("pipe");
return -1;
}
pid_t pid = fork();
if (pid == 0) {
child(fd);
}
close(fd[0]);// 父进程关闭读端
while (1) {
n = read(STDIN_FILENO, buf, 64);
write(fd[1], buf, n);
if (*buf == 'q') {
close(fd[1]);
exit(0);
}
}
return 0;
}

命令管道
(1)通过命令mkfifo创建管道
a)查看文件属性
当使用mkfifo创建hello文件后,查看文件信息
b)使用cat命令打印hello文件内容
接下来cat 命令被阻塞住。
开启另一个终端,执行:
echo “hello world” > hello

然后看到被阻塞的 cat 又继续执行完毕,在屏幕打印 “hello world” 。如果反过来执行上面两个命令,会发现先执行的那个总是被阻塞。
c)fifo文件特性
例题:编写两个程序,分别是发送端 pipe_send 和接收端面 pipe_recv 。程序 pipe_send 从标准输入接收字符,并发送到程序 pipe_recv ,同时 pipe_recv 将接收到的字符打印到屏幕。
程序:
/*************************************************************************
> File Name: pipe_send.c
> Author: xieluping
> Mail: 2234717859@qq.com
> Created Time: 2020年05月25日 星期一 19时58分10秒
************************************************************************/
#include<stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main() {
char buf[64];
int n = 0;
int fd = open("hello", O_WRONLY);
if (fd < 0) {
perror("open fifo");
return -1;
}
puts("has opend fifo");
while((n = read(STDIN_FILENO, buf, 64)) > 0) {
write(fd, buf, n);
if (buf[0] == 'q')
break;
}
close(fd);
return 0;
}
/*************************************************************************
> File Name: pipe_recv.c
> Author: xieluping
> Mail: 2234717859@qq.com
> Created Time: 2020年05月25日 星期一 19时58分47秒
************************************************************************/
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main() {
char buf[64];
int n = 0;
int fd = open("hello", O_RDONLY);
if (fd < 0) {
perror("open fifo");
return -1;
}
puts("has opened fifo");
while((n = read(fd, buf, 64)) > 0) {
write(STDOUT_FILENO, buf, n);
}
if (n == 0) {
puts("remote closed");
}
else {
perror("read fifo");
return -1;
}
close(fd);
return 0;
}
分别开启两个终端,分别运行 pipe_send 和 pipe_recv :

可以用组合按键结束上述两个进程。
2、IPC内核对象
例题:程序 ipccreate 用于在指定的键值上创建 ipc 内核对象。使用格式为 ./ipccreate ,比如./ipccreate 0 0x8888 表示在键值 0x8888 上创建共享内存。
程序:
/*************************************************************************
> File Name: ipccreate.c
> Author: xieluping
> Mail: 2234717859@qq.com
> Created Time: 2020年05月25日 星期一 20时15分08秒
************************************************************************/
#include<stdio.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/msg.h>
#include <sys/sem.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[]) {
if (argc < 3) {
printf("%s <ipc type> <key>\n", argv[0]);
return -1;
}
key_t key = strtoll(argv[2], NULL, 16);//key
char type = argv[1][0];//
char buf[64];
int id;
if (type == '0') {//创建共享内存
id = shmget(key, getpagesize(), IPC_CREAT | IPC_EXCL | 0644);
strcpy(buf, "share memory");
}
else if (type == '1') {//创建消息队列
id = msgget(key, IPC_CREAT | IPC_EXCL | 0644);
strcpy(buf, "message queue");
}
else if (type == '2') {//创建信号量
id = semget(key, 5, IPC_CREAT | IPC_EXCL | 0644);
strcpy(buf, "semaphore");
}
else {
printf("type must be 0, 1, or 2\n");
return -1;
}
if (id < 0) {
perror("get error");
return -1;
}
printf("create %s at 0x%x, id = %d\n", buf, key, id);
return 0;
}

获取ipc内核对象
程序:
/*************************************************************************
> File Name: ipcget.c
> Author: xieluping
> Mail: 2234717859@qq.com
> Created Time: 2020年05月25日 星期一 20时25分12秒
************************************************************************/
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/msg.h>
#include <sys/sem.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[]) {
if (argc < 3) {
printf("%s <ipc type> <key>\n", argv[0]);
return -1;
}
key_t key = strtoll(argv[2], NULL, 16);
char type = argv[1][0];
char buf[64];
int id;
if (type == '0') {
id = shmget(key, 0, 0);
strcpy(buf, "share memory");
}
else if (type == '1') {
id = msgget(key, 0);
strcpy(buf, "message queue");
}
else if (type == '2') {
id = semget(key, 0, 0);
strcpy(buf, "semaphore");
}
else {
printf("type must be 0, 1, or 2\n");
return -1;
}
if (id < 0) {
perror("get error");
return -1;
}
printf("get %s at 0x%x, id = %d\n", buf, key, id);
return 0;
}

3、共享内存
例题:编写一个程序 shmctl 可以用来创建、删除内核对象,也可以挂接、卸载共享内存,还可以打印、设置内核对象信息。具体使用方法具体见下面的说明:
./shmctl -c : 创建内核对象。
./shmctl -d : 删除内核对象。
./shmctl -v : 显示内核对象信息。
./shmctl -s : 设置内核对象(将权限设置为 0600 )。
./shmctl -a : 挂接和卸载共享内存(挂接 5 秒后,再执行 shmdt ,然后退出)。
程序:
/*************************************************************************
> File Name: shmctl.c
> Author: xieluping
> Mail: 2234717859@qq.com
> Created Time: 2020年05月25日 星期一 20时32分25秒
************************************************************************/
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#define ASSERT(res) if((res)<0){perror(__FUNCTION__);exit(-1);}
// 打印 ipc_perm
void printPerm(struct ipc_perm *perm) {
printf("euid of owner = %d\n", perm->uid);
printf("egid of owner = %d\n", perm->gid);
printf("euid of creator = %d\n", perm->cuid);
printf("egid of creator = %d\n", perm->cgid);
printf("mode = 0%o\n", perm->mode);
}
// 打印 ipc 内核对象信息
void printShmid(struct shmid_ds *shmid) {
printPerm(&shmid->shm_perm);
printf("segment size = %d\n", shmid->shm_segsz);
printf("last attach time = %s", ctime(&shmid->shm_atime));
printf("last detach time = %s", ctime(&shmid->shm_dtime));
printf("last change time = %s", ctime(&shmid->shm_ctime));
printf("pid of creator = %d\n", shmid->shm_cpid);
printf("pid of last shmat/shmdt = %d\n", shmid->shm_lpid);
printf("No. of current attaches = %ld\n", shmid->shm_nattch);
}
// 创建 ipc 内核对象
void create() {
int id = shmget(0x8888, 123, IPC_CREAT | IPC_EXCL | 0664);
printf("create %d\n", id);
ASSERT(id);
}
// IPC_STAT 命令使用,用来获取 ipc 内核对象信息
void show() {
int id = shmget(0x8888, 0, 0);
ASSERT(id);
struct shmid_ds shmid;
ASSERT(shmctl(id, IPC_STAT, &shmid));
printShmid(&shmid);
}
// IPC_SET 命令使用,用来设置 ipc 内核对象信息
void set() {
int id = shmget(0x8888, 123, IPC_CREAT | 0664);
ASSERT(id);
struct shmid_ds shmid;
ASSERT(shmctl(id, IPC_STAT, &shmid));
shmid.shm_perm.mode = 0600;
ASSERT(shmctl(id, IPC_SET, &shmid));
printf("set %d\n", id);
}
// IPC_RMID 命令使用,用来删除 ipc 内核对象
void rm() {
int id = shmget(0x8888, 123, IPC_CREAT | 0664);
ASSERT(id);
ASSERT(shmctl(id, IPC_RMID, NULL));
printf("remove %d\n", id);
}
// 挂接和卸载
void at_dt() {
int id = shmget(0x8888, 123, IPC_CREAT | 0664);
ASSERT(id);
char *buf = shmat(id, NULL, 0);
if (buf == (char*)-1) ASSERT(-1);
printf("shmat %p\n", buf);
sleep(5); // 等待 5 秒后,执行 shmdt
ASSERT(shmdt(buf));
printf("shmdt %p\n", buf);
}
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("usage: %s <option -c -v -s -d -a>\n", argv[0]);
return -1;
}
printf("I'm %d\n", getpid());
if (!strcmp(argv[1], "-c")) {
create();
}
else if (!strcmp(argv[1], "-v")) {
show();
}
else if (!strcmp(argv[1], "-s")) {
set();
}
else if (!strcmp(argv[1], "-d")) {
rm();
}
else if (!strcmp(argv[1], "-a")) {
at_dt();
}
return 0;
}

先在另一个终端执行 ./shmctl -a ,然后在当前终端执行 ./shmctl -v


4、消息队列
例题:程序 msg_send 和 msg_recv 分别用于向消息队列发送数据和接收数据。 msg_send 程序定义了一个结构体 Msg ,消息正文部分是结构体 Person 。该程序向消息队列发送了 10 条消息。
程序:
/*************************************************************************
> File Name: msg_send.c
> Author: xieluping
> Mail: 2234717859@qq.com
> Created Time: 2020年05月25日 星期一 20时48分54秒
************************************************************************/
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#define ASSERT(prompt,res) if((res)<0){perror(#prompt);exit(-1);}
typedef struct {
char name[20];
int age;
}Person;
typedef struct {
long type;
Person person;
}Msg;
int main(int argc, char *argv) {
int id = msgget(0x8888, IPC_CREAT | 0664);
ASSERT(msgget, id);
Msg msg[10] = {
{1, {"Luffy", 17}},
{1, {"Zoro", 19}},
{2, {"Nami", 18}},
{2, {"Usopo", 17}},
{1, {"Sanji", 19}},
{3, {"Chopper", 15}},
{4, {"Robin", 28}},
{4, {"Franky", 34}},
{5, {"Brook", 88}},
{6, {"Sunny", 2}}
};
int i;
for (i = 0; i < 10; ++i) {
int res = msgsnd(id, &msg[i], sizeof(Person), 0);
ASSERT(msgsnd, res);
}
return 0;
})
/*************************************************************************
> File Name: msg_recv.c
> Author: xieluping
> Mail: 2234717859@qq.com
> Created Time: 2020年05月25日 星期一 20时49分14秒
************************************************************************/
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#define ASSERT(prompt,res) if((res)<0){perror(#prompt);exit(-1);}
typedef struct {
char name[20];
int age;
}Person;
typedef struct {
long type;
Person person;
}Msg;
void printMsg(Msg *msg) {
printf("{ type = %ld, name = %s, age = %d }\n",
msg->type, msg->person.name, msg->person.age);
}
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("usage: %s <type>\n", argv[0]); return -1; }
long type = atol(argv[1]);
int id = msgget(0x8888, 0);
ASSERT(msgget, id);
Msg msg;
int res;
while(1) {
res = msgrcv(id, &msg, sizeof(Person), type, IPC_NOWAIT);
if (res < 0) {
if (errno == ENOMSG) {
printf("No message!\n");
break;
}
else {
ASSERT(msgrcv, res);
}
}
printMsg(&msg);
}
return 0;
}

先运行 ./msg_send ,再运行 ./msg_recv 。接收所有消息:
接收类型为 4 的消息,这时要重新运行 ./msg_send
接收类型小于等于 3 的所有消息,这是不用再运行 ./msg_send :

5、信号量
程序:
/*************************************************************************
> File Name: semop.c
> Author: xieluping
> Mail: 2234717859@qq.com
> Created Time: 2020年05月25日 星期一 21时05分05秒
************************************************************************/
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <stdio.h>
#include <stdlib.h>
#define R0 0
#define R1 1
#define R2 2
void printSem(int id) {
unsigned short vals[3] = { 0 };
semctl(id, 3, GETALL, vals);
printf("R0 = %d, R1= %d, R2 = %d\n\n", vals[0], vals[1], vals[2]);
}
int main() {
int id = semget(0x8888, 3, IPC_CREAT | IPC_EXCL | 0664);
// 打印信号量值
puts("信号量初始值(默认值)");
printSem(id);
// 1. 设置第 2 个信号量值
puts("1. 设置第 2 个信号量(R2)值为 20");
semctl(id, 2, SETVAL, 20);
printSem(id);
// 2. 同时设置 3 个信号量的值
puts("2. 同时设置 3 个信号量的值为 12, 5, 9");
unsigned short vals[3] = {12, 5, 9};
semctl(id, 0, SETALL, vals);
printSem(id);
// 3. 请求 2 个 R0 资源
puts("3. 请求 2 个 R0 资源");
struct sembuf op1 = {0, -2, 0};
semop(id, &op1, 1);
printSem(id);
// 4. 请求 3 个 R1 和 5 个 R2
puts("4. 请求 3 个 R1 和 5 个 R2");
struct sembuf ops1[2] = {
{1, -3, 0},
{2, -5, 0}
};
semop(id, ops1, 2);
printSem(id);
// 5. 释放 2 个 R1
puts("5. 释放 2 个 R1");
struct sembuf op2 = {1, 2, 0};
semop(id, &op2, 1);
printSem(id);
// 6. 释放 1 个 R0, 1 个 R1,3 个 R2
puts("6. 释放 1 个 R0, 1 个 R1,3 个 R2");
struct sembuf ops2[3] = {
{0, 1, 0},
{1, 1, 0},
{2, 3, 0}
};
semop(id, ops2, 3);
printSem(id);
// 7. 删除 ipc 内核对象
puts("7. 删除 ipc 内核对象");
semctl(id, 0, IPC_RMID);
return 0;
}

例题:使用信号量实现父子进程之间的同步,防止父子进程抢夺 CPU 。
/*************************************************************************
> File Name: mysem.c
> Author: xieluping
> Mail: 2234717859@qq.com
> Created Time: 2020年05月25日 星期一 21时11分20秒
************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<sys/ipc.h>
#include<sys/sem.h>
static int semid;
static void sem_set(){
if(semctl(semid,0,SETVAL,1)==-1)
{
perror("semctl");
exit(1);
}
}
static void sem_p(){
struct sembuf op = {0,-1,0};
if(semop(semid,&op,1) == -1){
perror("semop");
exit(1);
}
}
static void sem_v(){
struct sembuf op = {0,1,0};
if(semop(semid,&op,1) == -1){
perror("semop");
exit(1);
}
}
static void sem_del(){
if(semctl(semid,0,IPC_RMID) == -1){
perror("semctl");
exit(1);
}
}
int main(){
int i;
pid_t pid;
char ch = 'C';
semid = semget((key_t)1000,1,0664|IPC_CREAT);
if(semid == -1){
perror("semget");
exit(1);
}
sem_set();
pid = fork();
if(pid == -1){
sem_del();
exit(1);
}
else if (pid == 0)
ch = 'Z';
else
ch = 'C';
srand((unsigned int)getpid());
for(i=0;i<8;i++)
{
sem_p();
printf("%c",ch);
fflush(stdout);
sleep(rand()%4);
printf("%c",ch);
fflush(stdout);
sleep(1);
sem_v();
}
if(pid > 0) {
wait(NULL);
sem_del();
}
printf("\n");
return 0;
}

浙公网安备 33010602011771号