(命名)管道,信号量,消息队列,共享内存,信号,socket。
# 管道( pipe ):管道是一种半双工的通信方式,数据只能单向流动,而且只能在具有亲缘关系的进程间使用。进程的亲缘关系通常是指父子进程关系。
所需头文件 #include<unistd.h>
函数原型 int pipe(int fd[2])
- #include <unistd.h>
- #include <stdio.h>
- int main( void )
- {
- int filedes[2];
- char buf[80];
- pid_t pid;
- pipe( filedes );
- pid=fork();
- if (pid > 0)
- {
- printf( "This is in the father process,here write a string to the pipe.\n" );
- char s[] = "Hello world , this is write by pipe.\n";
- write( filedes[1], s, sizeof(s) );
- close( filedes[0] );
- close( filedes[1] );
- }
- else if(pid == 0)
- {
- printf( "This is in the child process,here read a string from the pipe.\n" );
- read( filedes[0], buf, sizeof(buf) );
- printf( "%s\n", buf );
- close( filedes[0] );
- close( filedes[1] );
- }
- waitpid( pid, NULL, 0 );
- return 0;
- }
# 有名管道 (named pipe) : 有名管道也是半双工的通信方式,但是它允许无亲缘关系进程间的通信。
mkfifo(PATH,0666)创建命名管道,各个进程使用open打开它,直接一个进程收一个进程发即可:
使用了mkfifo后,操作PATH就会阻塞,除非用open用O_NONBLOCK。不然open,access都会阻塞(我在嵌入式平台是这样,pc没试过)。
common.h
- #include <stdio.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #define FIFO_PATH "/tmp/myfifo"
server.c
- /*
- *将从FIFO收到到数据(字符)转换为大写,并输出到屏幕
- */
- #include "common.h"
- int main()
- {
- int ret;
- int fd;
- char buffer;
- int nread;
- int i;
- /*建立FIFO*/
- ret = mkfifo(FIFO_PATH, 0777);
- /*打开FIFO*/
- fd = open(FIFO_PATH, O_RDONLY);
- if(-1 == fd)
- {
- printf("error/n");
- return -1;
- }
- while(1)
- {
- nread = read(fd, &buffer, 1);
- if(nread > 0)
- {
- buffer = toupper(buffer);
- printf("%c", buffer);
- }
- }
- }
运行server后,可看到创建了文件/tmp/myfifo,这是mkfifo函数指定的命名管道的路径(名字)。
当然,系统不会真的在磁盘上创建这个文件。
client.c
- /*
- *读取输入,并写入FIFO
- */
- #include "common.h"
- int main()
- {
- int fd;
- int ret;
- char c;
- fd = open(FIFO_PATH, O_WRONLY);
- if(-1 == fd)
- {
- printf("error/n");
- return -1;
- }
- while(c = getchar())
- {
- write(fd, &c, 1);
- }
- }
# 信号量( semophore ) : 信号量是一个计数器,可以用来控制多个进程对共享资源的访问。它常作为一种锁机制,防止某进程正在访问共享资源时,其他进程也访问该资源。因此,主要作为进程间以及同一进程内不同线程之间的同步手段。
ftok,semget,semctl,semop,semtimedop.经常与ftok,shmget,shmmat,shmctl,shmdt用。
# 消息队列( message queue ) : 消息队列是由消息的链表,存放在内核中并由消息队列标识符标识。消息队列克服了信号传递信息少、管道只能承载无格式字节流以及缓冲区大小受限等缺点。
ftok,msgget,msgctl,msgsend,msgrcv
# 信号 ( sinal ) : 信号是一种比较复杂的通信方式,用于通知接收进程某个事件已经发生。
信号发送函数sigqueue和信号安装函数sigaction
# 共享内存( shared memory ) :共享内存就是映射一段能被其他进程所访问的内存,这段共享内存由一个进程创建,但多个进程都可以访问。共享内存是最快的 IPC 方式,它是针对其他进程间通信方式运行效率低而专门设计的。它往往与其他通信机制,如信号两,配合使用,来实现进程间的同步和通信。
ftok,semget,semctl,semop,semtimedop.经常与ftok,shmget,shmmat,shmctl,shmdt用。
# 套接字( socket ) : 套解口也是一种进程间通信机制,与其他通信机制不同的是,它可用于不同及其间的进程通信。