现今常用的进程间通信方式有:
- 管道(使用最简单)
- 信号(开销最小)
- 共享内存(无血缘关系)
- 套接字(最稳定)
管道的概念
这里指匿名管道,管道是一种最基本的IPC(进程间通信)机制,作用于有血缘关系的进程之间,比如父子、兄弟、叔侄进程,完成数据传递。
调用pipe()系统函数即可创建一个匿名管道。其特质如下:
- 其本质是一个伪文件(实际为内核缓冲区);
- 由两个文件描述符引用,一个表示读端,一个表示写端;
- 规定数据从管道的写端流入管道,从读端流出。
管道的局限性
管道的实现原理:管道实为内核使用环形队列机制,借助内核缓冲区(4K)实现。
管道的局限性:
- 数据不能进程自己写,自己读;
- 管道中数据不可反复读取,一旦读走,管道中不再存在;
- 采用半双工通信方式,数据只能在单方向上流动;
- 只能在有公共祖先的进程之间使用管道。
pipe函数
pipe函数,创建并打开管道。
#include <unistd.h>
int pipe(int fildes[2]);
参数:fildes[0] - 读端;fildes[1] - 写端;
返回值:0 - 成功;-1 - 失败,errno指使错误;
示例1
利用管道,实现父进程循环写,子进程循环读。
#include <stdio.h>
#include <unistd.h>
#include <error.h>
#include <string.h>
int main(int argc, char* argv[])
{
int ret = 0;
int fd[2];
pid_t pid;
char buf[256] = {'\0'};
ret = pipe(fd);
if (ret == -1){
perror("pipe failed!\n");
return -1;
}
pid = fork();
if (pid > 0) {
close(fd[0]); // 关闭读端
int i = 0;
while (i < 5) {
sprintf(buf, "father - %d\n", i++);
write(fd[1], buf, strlen(buf));
sleep(5);
}
close(fd[1]);
int status;
wait(&status);
}
else if (pid == 0) {
close(fd[1]); // 关闭写端
while (1)
{
ret = read(fd[0], buf, sizeof(buf)-1);
if (ret > 0) {
write(STDOUT_FILENO, buf, ret);
}
else {
printf("break, ret = %d\n", ret);
break;
}
}
close(fd[0]);
}
return 0;
}
管道的读写行为
使用管道注意以下4种情况(假设都是阻塞I/O操作,没有设置O_NONBLOCK标志):
- 如果所有指向管道写端的文件描述符都关闭了(管道写段引用计数为0),而仍有进程从管道的读端读数据,那么管道中剩余的数据都被读取后,再次read会返回0,就像读到文件末尾一样。
- 如果有指向管道写端的文件描述符没关闭(管道写端的引用计数大于0),而持有管道写端的进程也没有向管道中写数据,这时有进程从管道读端读数据,那么管道中剩余的数据都被读取后,再次read会阻塞,直到管道中有数据可读了才读取数据并返回。
- 如果所有指向管道读端的文件描述符都关闭了(管道读端引用计数为0),这时有进程向管道的写端write,那么该进程会收到信号SIGPIPE,通常会导致进程异常终止。当然也可以对SIGPIPE信号实施捕捉,不终止进程。
- 如果有指向管道读端的文件描述符都没有关闭(管道读端引用计数大于0),而持有管道读端的进程也没有从管道中读数据。这时有进程向管道写端写数据,那么在管道被写满时再次write会阻塞,直到管道中有空位置了才写入数据并返回。
总结:
读管道:
-
管道中有数据,read返回实际读到的字节数;
-
管道中无数据:
(1) 管道写端被全部关闭,read返回0;
(2) 写端没有被全部关闭,read阻塞等待,直到有数据写入管道。
写管道:
-
管道读端全部被关闭,写管道,进程收到信号SIGPIPE,进程异常终止(也可以捕捉SIGPIPE信号,使进程不终止);
-
管道读端没有全部关闭:
(1) 管道已满,write阻塞;
(2) 管道未满,write将数据写入,并返回实际写入的字节数;
示例2
测试管道读端都被关闭,引用计数为0时,进程向管道写端write会发生什么。
父进程子进程都关闭读端,父进程在写端写入数据,最终父进程捕捉到SIGPIPE信号。
#include <stdio.h>
#include <unistd.h>
#include <error.h>
#include <string.h>
#include <signal.h>
void sigProc(int signum)
{
printf("The progress %d catch the signal %d.\n", getpid(), signum);
}
int main(int argc, char* argv[])
{
int ret = 0;
int fd[2];
pid_t pid;
char buf[256];
ret = pipe(fd);
if (ret == -1){
perror("pipe failed!\n");
return -1;
}
pid = fork();
if (pid > 0){
printf("The father progress is %d.\n", getpid());
signal(SIGPIPE, sigProc);
close(fd[0]);
sleep(3); // 留时间给子进程关闭读端
strcpy(buf, "hello world");
printf("%s\n", buf);
write(fd[1], buf, strlen(buf));
close(fd[1]);
int status;
pid_t c_pid;
c_pid = wait(&status);
printf("the process %d end, status is %d.\n", c_pid, status);
}
else if (pid == 0){
printf("The child progress is %d.\n", getpid());
signal(SIGPIPE, sigProc);
close(fd[0]);
close(fd[1]);
printf("The child process %d close fd[0] and fd[1].\n", getpid());
sleep(10);
printf("the child progress end.\n");
}
return 0;
}
代码运行结果:
The father progress is 26336.
The child progress is 26337.
The child process 26337 close fd[0] and fd[1].
hello world
The progress 26336 catch the signal 13.
the child progress end.
the process 26337 end, status is 0.
实例3 - 兄弟进程通信
兄弟进程之间使用管道,实现“ls | wc -l”。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <error.h>
int main(int argc, char* argv[])
{
int fd[2];
int i = 0;
pid_t pid = 0;
int ret = 0;
ret = pipe(fd);
if (ret == -1)
{
perror("pipe error.\n");
return -1;
}
for (i=0; i<2; i++)
{
pid = fork();
if (pid == 0)
break;
}
if (i == 2)
{
close(fd[0]); // 父进程一定要关闭读端和写端
close(fd[1]);
wait(NULL);
wait(NULL);
}
else if (i == 0)
{
close(fd[0]);
dup2(fd[1], STDOUT_FILENO);
execlp("ls", "ls", NULL);
}
else if (i == 1)
{
close(fd[1]);
dup2(fd[0], STDIN_FILENO);
execlp("wc", "wc", "-l", NULL);
}
return 0;
}
管道的特殊读写行为
pipe管道,可以一个读端多个写端;也可以一个写端多个读端。但不推荐在实际开发中使用。
管道缓冲区的大小
可以使用ulimit -a命令来查看当前系统中创建管道文件所对应的内核缓冲区大小。“pipe size”通常为4K:
[nine@LinuxC pipe]$ ulimit -a
core file size (blocks, -c) 0
data seg size (kbytes, -d) unlimited
scheduling priority (-e) 0
file size (blocks, -f) unlimited
pending signals (-i) 31078
max locked memory (kbytes, -l) 64
max memory size (kbytes, -m) unlimited
open files (-n) 1024
pipe size (512 bytes, -p) 8
POSIX message queues (bytes, -q) 819200
real-time priority (-r) 0
stack size (kbytes, -s) 8192
cpu time (seconds, -t) unlimited
max user processes (-u) 4096
virtual memory (kbytes, -v) unlimited
file locks (-x) unlimited
[nine@LinuxC pipe]$
也可以使用fpathconf()函数来查看,name取值可以为_PC_PIPE_BUF。
#include <unistd.h>
long fpathconf(int fd, int name);
FIFO 命名管道
相较于使用信号、或套接字实现进程间通信,使用管道要简单的多。但缺点是:
- 只能单向通信,双向通信需建立两个管道;
- 只能用于父子、兄弟进程(有共同的祖先)间通信。这一点可用后来的fifo有名管道解决。
FIFO常被称为命名管道,以区分管道pipe。管道pipe只能用于“有血缘关系”的进程之间。但通过FIFO,不相关的进程也能交换数据。
FIFO是Linux基础文件类型中的一种。但,FIFO文件在磁盘上没有数据块,仅仅用来标识内核中一条通道。各进程可以打开这个文件进行read/write,实际上是在读写内核通道,这样就实现了进程间通信。
创建方式:
-
命令:mkfifo 管道名;
-
库函数:int mkfifo(const char *pathname, mode_t mode);
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);
返回值:成功:0;失败:-1,errno指示错误码;
一旦使用mkfifo创建了一个FIFO,就可以使用open打开它,常见的文件I/O函数都可用于fifo。如:close、read、write、unlink等。
示例4 - fifo
建立两个无血缘关系的进程,使用fifo实现通信。一个进程写,一个进行读并输出至屏幕。
写进程:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <error.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc, char* argv[])
{
int i = 0;
int fd = 0;
char buf[256] = {'\0'};
fd = open(argv[1], O_WRONLY);
if (fd < 0){
perror("open error.\n");
return -1;
}
while(i<200)
{
sprintf(buf, "test %d.\n", i++);
write(fd, buf, strlen(buf));
sleep(1);
}
close(fd);
return 0;
}
读进程:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <error.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc, char* argv[])
{
int len = 0;
int fd = 0;
char buf[256] = {'\0'};
fd = open(argv[1], O_RDONLY);
if (fd < 0){
perror("open error.\n");
return -1;
}
while (1)
{
len = read(fd, buf, sizeof(buf));
write(STDOUT_FILENO, buf, len);
sleep(3);
}
close(fd);
return 0;
}
最后使用mkfifo命令建立一个命名管道,如testfifo,并分别运行fifo_w和fifo_r程序:
mkfifo testfifo
./fifo_w testfifo
另起一个终端
./fifo_r testfifo