Linux系统编程——进程间通信(单机)

下文转自:
https://blog.csdn.net/chenpuo/article/details/81183678

前言

进程间通信(IPC,InterProcess Communication)是指在不同进程之间传播或交换信息。

IPC的方式通常有管道(包括无名管道和命名管道)、消息队列、信号量、共享存储、Socket、Streams等。其中 Socket和Streams支持不同主机上的两个进程IPC。

一、管道

通常指无名管道,是UNIX系统IPC最古老的形式。

1.特点

1.它是半双工的(即数据智能在一个方向上流动),具有固定的读端fd[0]和写端fd[1]
2.它只能用于具有亲缘关系的进程之间的通信。(父子进程或者兄弟进程之间)
3.它可以看成是一种特殊的文件,对于它的读写也可以使用普通的read,write等函数。但是它不是普通的文件,不属于其他任何文件系统,并且只存在于内存中。

2.原型
#include <unistd.h>

       int pipe(int pipefd[2]);

当一个管道建立时,它会创建两个文件描述符:fd[0]为读而打开,fd[1]为写而打开。如下图:
在这里插入图片描述
要关闭管道只需将这两个文件描述符关闭即可

3.例子

单个进程中的管道几乎没有任何用处。所以,通常调用 pipe 的进程接着调用 fork,这样就创建了父进程与子进程之间的 IPC 通道。如下图所示:
在这里插入图片描述
若要数据流从父进程流向子进程,则关闭父进程的读端(fd[0])与子进程的写端(fd[1]);反之,则可以使数据流从子进程流向父进程。

1 #include<stdio.h>
 2 #include<unistd.h>
 3 
 4 int main()
 5 {
 6     int fd[2];  // 两个文件描述符
 7     pid_t pid;
 8     char buff[20];
 9 
10     if(pipe(fd) < 0)  // 创建管道
11         printf("Create Pipe Error!\n");
12 
13     if((pid = fork()) < 0)  // 创建子进程
14         printf("Fork Error!\n");
15     else if(pid > 0)  // 父进程
16     {
17         close(fd[0]); // 关闭读端
18         write(fd[1], "hello world\n", 12);
19     }
20     else		//子进程
21     {
22         close(fd[1]); // 关闭写端
23         read(fd[0], buff, 20);
24         printf("%s", buff);
25     }
26
27     return 0;
28	}

例子2:父进程往管道写数据,子进程读数据
代码:

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

int main()
{
        int fd[2];

        pid_t pid;

        char readbuf[128];

        if(pipe(fd)==-1){
                printf("creat pipe failed\n");
        }
        pid=fork();

        if(pid<0){
                printf("creat child failed\n");
        }
        else if(pid>0){
                sleep(3);
                printf("this is father\n");
                close(fd[0]);
                write(fd[1],"hello from father",strlen("hello from father"));
        }else {
                printf("this is child\n");
                close(fd[1]);
                read(fd[0],readbuf,1024);
                printf("read from father:%s\n",readbuf);
                exit(-1);
        }
        return 0;
}

运行结果:

CLC@Embed_Learn:~/lianxi4$ gcc demo4.c
CLC@Embed_Learn:~/lianxi4$ ./a.out
this is father
this is child
read from father:hello from father
二、命名管道FIFO
1.特点

①.FIFO可以在无关的进程之间交换数据
②.FIFO有路径名与之相关联,它以一种特殊设备文件形式存在于文件系统中。

2.原型
 #include <sys/types.h>
 #include <sys/stat.h>

       int mkfifo(const char *pathname, mode_t mode);

其中的 mode 参数与open函数中的 mode 相同。一旦创建了一个 FIFO,就可以用一般的文件I/O函数操作它。

当 open 一个FIFO时,是否设置非阻塞标志(O_NONBLOCK)的区别:

若没有指定O_NONBLOCK(默认),只读 open 要阻塞到某个其他进程为写而打开此 FIFO。类似的,只写 open 要阻塞到某个其他进程为读而打开它。

若指定了O_NONBLOCK,则只读 open 立即返回。而只写 open 将出错返回 -1 如果没有进程已经为读而打开该 FIFO,其errno置ENXIO

3.例子

FIFO的通信方式类似于在进程中使用文件来传输数据,只不过FIFO类型文件同时具有管道的特性。在数据读出时,FIFO管道中同时清除数据,并且“先进先出”。
下面的例子演示了使用 FIFO 进行 IPC 的过程:

write_fifo.c 向管道中写数据

1 #include<stdio.h>
 2 #include<stdlib.h>   // exit
 3 #include<fcntl.h>    // O_WRONLY
 4 #include<sys/stat.h>
 5 #include<time.h>     // time
 6 
 7 int main()
 8 {
 9     int fd;
10     int n, i;
11     char buf[1024];
12     time_t tp;
13 
14     printf("I am %d process.\n", getpid()); // 说明进程ID
15     
16     if((fd = open("fifo1", O_WRONLY)) < 0) // 以写打开一个FIFO 
17     {
18         perror("Open FIFO Failed");
19         exit(1);
20     }
21 
22     for(i=0; i<10; ++i)
23     {
24         time(&tp);  // 取系统当前时间
25         n=sprintf(buf,"Process %d's time is %s",getpid(),ctime(&tp));
26         printf("Send message: %s", buf); // 打印
27         if(write(fd, buf, n+1) < 0)  // 写入到FIFO中
28         {
29             perror("Write FIFO Failed");
30             close(fd);
31             exit(1);
32         }
33         sleep(1);  // 休眠1秒
34     }
35 
36     close(fd);  // 关闭FIFO文件
37     return 0;
38	}

read_fifo.c 从管道中读数据

1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<errno.h>
 4 #include<fcntl.h>
 5 #include<sys/stat.h>
 6 
 7 int main()
 8 {
 9     int fd;
10     int len;
11     char buf[1024];
12 
13     if(mkfifo("fifo1", 0666) < 0 && errno!=EEXIST) // 创建FIFO管道
14         perror("Create FIFO Failed");
15 
16     if((fd = open("fifo1", O_RDONLY)) < 0)  // 以读打开FIFO
17     {
18         perror("Open FIFO Failed");
19         exit(1);
20     }
21     
22     while((len = read(fd, buf, 1024)) > 0) // 读取FIFO管道
23         printf("Read message: %s", buf);
24 
25     close(fd);  // 关闭FIFO文件
26     return 0;
27 }
三.消息队列

消息队列,是消息的链接表,存放在内核中。一个消息队列由一个标识符(即队列ID)来标识。

1.特点

1.消息队列是面向记录的,其中的消息具有特定的格式以及特定的优先级。

2.消息队列独立于发送与接收进程。进程终止时,消息队列及其内容并不会被删除。

3.消息队列可以实现消息的随机查询,消息不一定要以先进先出的次序读取,也可以按消息的类型读取

2.原型
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
		/* 创建或打开消息队列:成功返回队列ID,失败-1*/
       int msgget(key_t key, int msgflg);

		/* 添加消息:成功返回0, 失败-1*/
       int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);

		/* 读取消息:成功返回消息数据的长度, 失败-1*/
	   ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg);

		/* 控制消息队列:成功返回0,失败-1*/
	   int msgctl(int msqid, int cmd, struct msqid_ds *buf);
		函数的第一个参数msgqid 是消息队列对象的标识符。
		第二个参数是函数要对消息队列进行的操作,它可以是:
	**IPC_STAT**
	取出系统保存的消息队列的msqid_ds 数据,并将其存入参数buf 指向的msqid_ds 结构
	中。
	**IPC_SET**
	设定消息队列的msqid_ds 数据中的msg_perm 成员。设定的值由buf 指向的msqid_ds
	结构给出。
	**IPC_RMID**
	将队列从系统内核中删除。

在以下两种情况下,msgget将创建一个新的消息队列:

1.如果没有与键值key相对应的消息队列,并且flag中包含了IPC_CREAT标志位。
2.key参数为IPC_PRIVATE。
函数msgrcv在读取消息队列时,type参数有下面几种情况:

type == 0,返回队列中的第一个消息;
type > 0,返回队列中消息类型为 type 的第一个消息;
type < 0,返回队列中消息类型值小于或等于 type 绝对值的消息,如果有多个,则取类型值最小的消息。
可以看出,type值非 0 时用于以非先进先出次序读消息。也可以把 type 看做优先级的权值。(其他的参数解释,请自行Google之)

3.例子

下面写了一个简单的使用消息队列进行IPC的例子,服务端程序一直在等待特定类型的消息,当收到该类型的消息以后,发送另一种特定类型的消息作为反馈,客户端读取该反馈并打印出来。

下面用到ftok函数
系统建立IPC通讯 (消息队列、信号量和共享内存) 时必须指定一个ID值。通常情况下,该id值通过ftok函数得到。

头文件
#include <sys/types.h>
#include <sys/ipc.h>
函数原型:
key_t ftok( const char * fname, int id )
fname就是你指定的文件名(已经存在的文件名),一般使用当前目录,如:
key_t key;
key = ftok(".", 1); 这样就是将fname设为当前目录。
id是子序号。虽然是int类型,但是只使用8bits(1-255)。
在一般的UNIX实现中,是将文件的索引节点号取出,前面加上子序号得到key_t的返回值。
如指定文件的索引节点号为65538,换算成16进制为0x010002,而你指定的ID值为38,换算成16进制为0x26,则最后的key_t返回值为0x26010002。
查询文件索引节点号的方法是: ls -i
当删除重建文件后,索引节点号由操作系统根据当时文件系统的使用情况分配,因此与原来不同,所以得到的索引节点号也不同。

msg_server.c

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <sys/msg.h>
 4 
 5 // 用于创建一个唯一的key
 6 #define MSG_FILE "/etc/passwd"
 7 
 8 // 消息结构
 9 struct msg_form {
10     long mtype;
11     char mtext[256];
12 };
13 
14 int main()
15 {
16     int msqid;
17     key_t key;
18     struct msg_form msg;
19     
20     // 获取key值
21     if((key = ftok(MSG_FILE,'z')) < 0)
22     {
23         perror("ftok error");
24         exit(1);
25     }
26 
27     // 打印key值
28     printf("Message Queue - Server key is: %d.\n", key);
29 
30     // 创建消息队列
31     if ((msqid = msgget(key, IPC_CREAT|0777)) == -1)
32     {
33         perror("msgget error");
34         exit(1);
35     }
36 
37     // 打印消息队列ID及进程ID
38     printf("My msqid is: %d.\n", msqid);
39     printf("My pid is: %d.\n", getpid());
40 
41     // 循环读取消息
42     for(;;) 
43     {
44         msgrcv(msqid, &msg, 256, 888, 0);// 返回类型为888的第一个消息
45         printf("Server: receive msg.mtext is: %s.\n", msg.mtext);
46         printf("Server: receive msg.mtype is: %d.\n", msg.mtype);
47 
48         msg.mtype = 999; // 客户端接收的消息类型
49         sprintf(msg.mtext, "hello, I'm server %d", getpid());
50         msgsnd(msqid, &msg, sizeof(msg.mtext), 0);
51     }
52     return 0;
53 }

msg_client.c

1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <sys/msg.h>
 4 
 5 // 用于创建一个唯一的key
 6 #define MSG_FILE "/etc/passwd"
 7 
 8 // 消息结构
 9 struct msg_form {
10     long mtype;
11     char mtext[256];
12 };
13 
14 int main()
15 {
16     int msqid;
17     key_t key;
18     struct msg_form msg;
19 
20     // 获取key值
21     if ((key = ftok(MSG_FILE, 'z')) < 0) 
22     {
23         perror("ftok error");
24         exit(1);
25     }
26 
27     // 打印key值
28     printf("Message Queue - Client key is: %d.\n", key);
29 
30     // 打开消息队列
31     if ((msqid = msgget(key, IPC_CREAT|0777)) == -1) 
32     {
33         perror("msgget error");
34         exit(1);
35     }
36 
37     // 打印消息队列ID及进程ID
38     printf("My msqid is: %d.\n", msqid);
39     printf("My pid is: %d.\n", getpid());
40 
41     // 添加消息,类型为888
42     msg.mtype = 888;
43     sprintf(msg.mtext, "hello, I'm client %d", getpid());
44     msgsnd(msqid, &msg, sizeof(msg.mtext), 0);
45 
46     // 读取类型为777的消息
47     msgrcv(msqid, &msg, 256, 999, 0);
48     printf("Client: receive msg.mtext is: %s.\n", msg.mtext);
49     printf("Client: receive msg.mtype is: %d.\n", msg.mtype);
50     return 0;
51 }
四、共享内存

共享内存(Shared Memory),指两个或多个进程共享一个给定的存储区。

1.特点

1.共享内存是最快的一种 IPC,因为进程是直接对内存进行存取。

2.因为多个进程可以同时操作,所以需要进行同步。

3.信号量+共享内存通常结合在一起使用,信号量用来同步对共享内存的访问。

2.原型
#include <sys/ipc.h>
#include <sys/shm.h>
		/* 创建或获取一个共享内存:成功返回ID,失败-1*/
       int shmget(key_t key, size_t size, int shmflg);
       
        /* 连接共享内存到当前进程的地址空间:成功返回只想共享内存的指针,失败-1*/
       void *shmat(int shmid, const void *shmaddr, int shmflg);
		
		/* 断开与共享内存的连接:成功返回0,失败-1*/
       int shmdt(const void *shmaddr);

		/* 控制共享内存的相关信息:成功0,失败-1*/
	   int shmctl(int shmid, int cmd, struct shmid_ds *buf);

函数的参数解析参考博文:
https://blog.csdn.net/qq_27664167/article/details/81277096

3.例子

创建一个共享内存,让服务端和客户端同时读取共享内存上的数据
shm_write.c

#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>


int main()
{
    int shmid;
    char *shmaddr;

    key_t key;
    key = ftok(".", 1);

    /* 1.创建共享内存*/
    shmid = shmget(key, 1024*4, IPC_CREAT|0666);
    if(shmid == -1){
        perror("shmget error!\n");
        exit(-1);
    }

    /* 2。内存地址映射*/
    shmaddr = shmat(shmid, 0, 0);
    if(*shmaddr == -1){
        perror("shmat error!\n");
        exit(-1);
    }
    printf("shmat ok\n");

    /* 3.向内存地址写入数据*/
    strcpy(shmaddr, "qiuyiguang");

    sleep(5);
    /* 4.关闭共享内存*/
    shmdt(shmaddr);
    shmctl(shmid, IPC_RMID, 0);

    printf("quit\n");

    return 0;
}

shm_read.c

#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>



int main()
{
    int shmid;
    char *shmaddr;

    key_t key;
    key = ftok(".", 1);

    /* 1.创建共享内存*/
    shmid = shmget(key, 1024*4, IPC_CREAT|0666);
    if(shmid == -1){
        perror("shmget error!\n");
        exit(-1);
    }

    /* 2。内存地质映射*/
    shmaddr = shmat(shmid, 0, 0);
    if(*shmaddr == -1){
        perror("shmat error!\n");
        exit(-1);
    }
    printf("shmat ok\n");

    /* 3.打印内存地址中的数据*/
    printf("data: %s\n",shmaddr);
   
    /* 4.关闭共享内存*/
    shmdt(shmaddr);
    printf("quit\n");

    return 0;
}
五.信号量

信号量(semaphore)与已经介绍过的 IPC 结构不同,它是一个计数器。信号量用于实现进程间的互斥与同步,而不是用于存储进程间通信数据。

推荐博文:
https://www.cnblogs.com/wuyepeng/p/9748552.html

1.特点

1.信号量用于进程间同步,若要在进程间传递数据需要结合共享内存。

2.信号量基于操作系统的 PV (P:拿锁,V:解锁)操作,程序对信号量的操作都是原子操作。

3.每次对信号量的 PV 操作不仅限于对信号量值加 1 或减 1,而且可以加减任意正整数。

4.支持信号量组。

2.原型
 #include <sys/types.h>
 #include <sys/ipc.h>
 #include <sys/sem.h>
	
		/* 创建信号量:成功返回ID,失败-1*/
       int semget(key_t key, int nsems, int semflg);

		/* 改变信号量的值:成功返回0,失败-1*/
       int semop(int semid, struct sembuf *sops, size_t nsops);

		/* 删除和初始化信号量*/
	   int semctl(int semid, int semnum, int cmd, ...);
3.例子
1 #include<stdio.h>
  2 #include<stdlib.h>
  3 #include<sys/sem.h>
  4 
  5 // 联合体,用于semctl初始化
  6 union semun
  7 {
  8     int              val; /*for SETVAL*/
  9     struct semid_ds *buf;
 10     unsigned short  *array;
 11 };
 12 
 13 // 初始化信号量
 14 int init_sem(int sem_id, int value)
 15 {
 16     union semun tmp;
 17     tmp.val = value;	/* 刚开始锁的数量*/
 18     if(semctl(sem_id, 0, SETVAL, tmp) == -1)
 19     {
 20         perror("Init Semaphore Error");
 21         return -1;
 22     }
 23     return 0;
 24 }
 25 
 26 // P操作:
 27 //    若信号量值为1,获取资源并将信号量值-1 
 28 //    若信号量值为0,进程挂起等待
 29 int sem_p(int sem_id)
 30 {
 31     struct sembuf sbuf;
 32     sbuf.sem_num = 0; /*序号*/
 33     sbuf.sem_op = -1; /*P操作,拿锁后减1*/
 34     sbuf.sem_flg = SEM_UNDO;
 35 
 36     if(semop(sem_id, &sbuf, 1) == -1)
 37     {
 38         perror("P operation Error");
 39         return -1;
 40     }
 41     return 0;
 42 }
 43 
 44 // V操作:
 45 //    释放资源并将信号量值+1
 46 //    如果有进程正在挂起等待,则唤醒它们
 47 int sem_v(int sem_id)
 48 {
 49     struct sembuf sbuf;
 50     sbuf.sem_num = 0; /*序号*/
 51     sbuf.sem_op = 1;  /*V操作,解锁后加1*/
 52     sbuf.sem_flg = SEM_UNDO;
 53 
 54     if(semop(sem_id, &sbuf, 1) == -1)
 55     {
 56         perror("V operation Error");
 57         return -1;
 58     }
 59     return 0;
 60 }
 61 
 62 // 删除信号量集
 63 int del_sem(int sem_id)
 64 {
 65     union semun tmp;
 66     if(semctl(sem_id, 0, IPC_RMID, tmp) == -1)
 67     {
 68         perror("Delete Semaphore Error");
 69         return -1;
 70     }
 71     return 0;
 72 }
 73 
 74 
 75 int main()
 76 {
 77     int sem_id;  // 信号量集ID
 78     key_t key;  
 79     pid_t pid;
 80 
 81     // 获取key值
 82     if((key = ftok(".", 'z')) < 0)
 83     {
 84         perror("ftok error");
 85         exit(1);
 86     }
 87 
 88     // 创建信号量集,其中只有一个信号量
 89     if((sem_id = semget(key, 1, IPC_CREAT|0666)) == -1)
 90     {
 91         perror("semget error");
 92         exit(1);
 93     }
 94 
 95     // 初始化:初值设为0资源被占用
 96     init_sem(sem_id, 0);
 97 
 98     if((pid = fork()) == -1)
 99         perror("Fork Error");
100     else if(pid == 0) /*子进程*/ 
101     {
102         sleep(2);
103         printf("Process child: pid=%d\n", getpid());
104         sem_v(sem_id);  /*释放资源*/
105     }
106     else  /*父进程*/
107     {
108         sem_p(sem_id);   /*等待资源*/
109         printf("Process father: pid=%d\n", getpid());
110         sem_v(sem_id);   /*释放资源*/
111         del_sem(sem_id); /*删除信号量集*/
112     }
113     return 0;
114 }

例子2:利用pv锁保证子进程先走,然后再走父进程
代码:

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <stdio.h>

union semun
{
    int val;  //使用的值
    struct semid_ds *buf;  //IPC_STAT、IPC_SET 使用的缓存区
    unsigned short *arry;  //GETALL,、SETALL 使用的数组
    struct seminfo *__buf; // IPC_INFO(Linux特有) 使用的缓存区
};

void pGetkey(int id)//拿锁
{
        struct sembuf set;
        set.sem_num=0;
        set.sem_op=-1;
        set.sem_flg=SEM_UNDO;
        semop(id,&set, 1);
        printf("getkey\n");

}

void vPutkey(int id)//放锁
{
        struct sembuf set;
        set.sem_num=0;
                set.sem_op=1;
        set.sem_flg=SEM_UNDO;
        semop(id,&set, 1);
        printf("put back the key\n");

}


int main(int argc,char *argv[])
{
        key_t key;
        int semid;

        key=ftok(".",2);

        semid=semget(key,1,IPC_CREAT|0666);//获取/创建信号量

        union semun initsem;
        initsem.val=0;


        semctl(semid,0,SETVAL,initsem);//初始化信号量,,操作第0个信号量,SETVAL设置信号量的值,设置为initsem

        int pid=fork();
               if(pid>0){

                pGetkey(semid);/拿锁
                printf("this is father\n");
                vPutkey(semid);//放锁

                semctl(semid,0,IPC_RMID);//销毁这个锁

        }
        else if(pid==0){
                printf("this is child\n");
                vPutkey(semid);

        }else{
                printf("fork failed\n");
        }


        return 0;
}

运行结果:

CLC@Embed_Learn:~/lianxi4$ ./a.out
this is child
put back the key
getkey
this is father
put back the key
五种通讯方式总结

1.匿名管道:速度慢,容量有限**,只有父子进程能通讯**

2.命名管道:可以在进程之间通讯,但速度慢

3.消息队列:容量收到系统限制,且要注意第一次读的时候,要考虑上一次没有读完数据的问题**

4.共享内存:能够很容易控制容量,速度快,但要保持同步。比如一个进程在写的时候,另一个进程要注意读写的问题,相当于线程中的线程安全,当然,共享内存区同样可以用作线程间通讯,不过没这个必要,线程间本来就已经共享了同一进程内的一块内存

5.信号量:不能传递复杂消息,只能用来同步

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值