Linux进程间通信(IPC)
一、管道:
1. 无名管道: 打开与关闭管道: #include <unistd.h> int pipe(int filedes[2]); filedes[0]用于读出数据,读取时必须关闭写入端,即close(filedes[1]); filedes[1]用于写入数据,写入时必须关闭读取端,即close(filedes[0])。 2. 有名管道FIFO: 创建FIFO: #include <sys/types.h> #include <sys/stat.h> int mkfifo(const char *pathname, mode_t mode); 读写管道与读写文件的操作相同。
二、System V FIFO:
1. 共享内存: 创建共享内存区: #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> int shmget(key_t key, int size, int flags); 附加/分离共享内存区: #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> char *shmat(int shmid, char *shmaddr, int flags); int shmdt(char *shmadr); 2. 消息队列: 创建消息队列: #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> int msgget(key_t key, int flags); 读写消息: #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> 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 <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> int int msgctl(int msqid, int cmd, struct msqid_ds *buf); cmd为IPC_RMID时为删除队列msqid。 3. 信号量: 创建/打开: #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> 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 <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> int semctl(int semid, int semnum, int cmd, union semun arg); 当cmd为IPC_RMID时为删除信号量集。