---
title: "Linux进程间通信(IPC)"
author: "gqf2008"
date: "2009-11-07T21:26:55Z"
tags: ["Linux", "数据结构"]
slug: "linux-ipc"
draft: false
lastmod: "2009-11-07T21:26:55Z"
id: 512187
url: "https://gqf2008.iteye.com/blog/512187"
---

Linux进程间通信(IPC)

一、管道：

1\. 无名管道： 打开与关闭管道： #include &lt;unistd.h&gt; int pipe(int filedes\[2]); filedes\[0]用于读出数据，读取时必须关闭写入端，即close(filedes\[1]); filedes\[1]用于写入数据，写入时必须关闭读取端，即close(filedes\[0])。 2. 有名管道FIFO： 创建FIFO： #include &lt;sys/types.h&gt; #include &lt;sys/stat.h&gt; int mkfifo(const char \*pathname, mode\_t mode); 读写管道与读写文件的操作相同。

二、System V FIFO：

1\. 共享内存： 创建共享内存区： #include &lt;sys/types.h&gt; #include &lt;sys/ipc.h&gt; #include &lt;sys/shm.h&gt; int shmget(key\_t key, int size, int flags); 附加/分离共享内存区： #include &lt;sys/types.h&gt; #include &lt;sys/ipc.h&gt; #include &lt;sys/shm.h&gt; char \*shmat(int shmid, char \*shmaddr, int flags); int shmdt(char \*shmadr); 2. 消息队列： 创建消息队列： #include &lt;sys/types.h&gt; #include &lt;sys/ipc.h&gt; #include &lt;sys/msg.h&gt; int msgget(key\_t key, int flags); 读写消息： #include &lt;sys/types.h&gt; #include &lt;sys/ipc.h&gt; #include &lt;sys/msg.h&gt; int msgsnd(int msqid, const void \*prt, size\_t nbytes, int flags); int msgrcv(int msqid, void \*prt, size\_t nbytes, int flags); prt是指向msgbuf结构的指针，msgbuf在中定义如下： struct msgbuf { long mtype; char mtext\[1]; }; msgbuf结构可以自由更改设置。 删除消息队列： #include &lt;sys/types.h&gt; #include &lt;sys/ipc.h&gt; #include &lt;sys/msg.h&gt; int int msgctl(int msqid, int cmd, struct msqid\_ds \*buf); cmd为IPC\_RMID时为删除队列msqid。 3. 信号量： 创建/打开： #include &lt;sys/types.h&gt; #include &lt;sys/ipc.h&gt; #include &lt;sys/sem.h&gt; int semget(key\_t key, int nsems, int flags); int semop(int semid, struct sembuf \*semops, unsigned nops); sembuf结构定义如下： struct sembuf { short sem\_num; /* Semaphore number \*/ short sem\_op; /* The operation to perform \*/ short sem\_flg; /* Flags controlling the operation \*/ }; 如果sem\_op为正，表示资源被释放，信号量增加。 如果sem\_op为负，表示资源被申请，信号量减少。 如果sem\_op为0，表示进程被阻塞直到信号量变为0。 控制和删除： #include &lt;sys/types.h&gt; #include &lt;sys/ipc.h&gt; #include &lt;sys/sem.h&gt; int semctl(int semid, int semnum, int cmd, union semun arg); 当cmd为IPC\_RMID时为删除信号量集。