1 什么是管道通信
管道(pipe)是单向的、先进先出的、无结构的、固定大小的字节流,它把一个进程的标准输出和另一个进程的标准输入连接在一起。写进程在管道的尾端写入数据,读进程在管道的首端读出数据。数据读出后将从管道中移走,其它读进程都不能再读到这些数据。管道提供了简单的流控制机制。进程试图读空管道时,在有数据写入管道前,进程将一直阻塞。同样,管道已经满时,进程再试图写管道,在其它进程从管道中移走数据之前,写进程将一直阻塞。管道主要用于不同进程间通信。
2 怎么用管道通信
函数原型:
int pipe( int fd[2]);
参数:fd[2] 。它接受一个参数,也就是一个包括两个整数的数组。如果系统调用成功,此数组将包括管道使用的两个文件描述符。创建一个管道之后,一般情况下进程将产生一个新的进程。fd[0]用于读取管道,fd[1]用于写入管道。
返回值:如果系统调用成功,返回0。如果系统调用失败返回-1:
3 示例1
#include<unistd.h>
#include<memory.h>
#include<errno.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
int main()
{
int fd[2];
int rtn;
char buff_read[100];
char buff_write[100];
memset(buff_read,0,sizeof(buff_read));
memset(buff_write,0,sizeof(buff_write));
// 字符串赋值
strcpy(buff_write, "hello world !");
// 创建管道
rtn = pipe(fd);
// 打印是否创建成功
if (rtn == 0)
printf("creat pipe ok\n");
else
printf("crest pipe fail\n");
// 写管道
write(fd[1],buff_write,sizeof(buff_write));
// 读管道
read(fd[0],buff_read,100);
printf("%s\n",buff_read);
}
运行结果:
root@ubuntu:/mnt/share/test# gcc -o pipe_3 pipe_3.c
root@ubuntu:/mnt/share/test# ./pipe_3
creat pipe ok
hello world !
4 示例2
#include<unistd.h>
#include<memory.h>
#include<errno.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
int main()
{
int fd[2];
int rtn;
int pid;
char buff_read[100];
char buff_write[100];
memset(buff_read,0,sizeof(buff_read));
memset(buff_write,0,sizeof(buff_write));
// 字符串赋值
strcpy(buff_write, "hello world !");
// 创建管道
rtn = pipe(fd);
// 打印是否创建成功
if (rtn == 0)
printf("creat pipe ok\n");
else
printf("crest pipe fail\n");
// 创建子进程
pid = fork();
if (pid == 0){ // 子进程
close(fd[1]); // 关闭写管道
read(fd[0],buff_read,sizeof(buff_read)); // 读
close(fd[0]);
printf("receive %s\n",buff_read);
}
else if (pid > 0){ // 父进程
close(fd[0]); // 关闭读管道
write(fd[1],buff_write,sizeof(buff_write)); // 写
close(fd[1]);
sleep(2); // 等待一会,等子进程接收到后再返回
}
else {
// 异常处理
fprintf(stderr,"ERROR:fork() failed!\n");
}
}
运行结果:
root@ubuntu:/mnt/share/test# gcc -o pipe_3 pipe_3.c
root@ubuntu:/mnt/share/test# ./pipe_3
creat pipe ok
receive hello world !
root@ubuntu:/mnt/share/test#