半双工管道
管道:将某个进程的输出和另一个进程的输入相连接的单向通信的方法。故称为“半双工” 在shell 中管道用“|”表示
pipe()函数
#include <unistd.h>
int pipe(int filedes[2]);
// filedes 文件描述符数组,用于保存管道返回的两个文件描述符。(第一个读,第二个写)
// 成功返回0 否则 -1.
例子
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
int main()
{
int result = -1;
int fd[2],nbytes; // 声明两个文件描述符 ,一个读 一个写。
pid_t pid;
char string[] = "hello pipe";
char readbuffer[80];
int* write_fd = &fd[1]; // 第二个为写。
int* read_fd = &fd[0];
result = pipe(fd); // 创建管道
if(-1 == result)
{
printf("error \n");
return -1;
}
pid = fork(); // 复制进程。
if(-1 == pid)
{
printf("fork error");
return -1;
}
if(0 == pid)
{
close(*read_fd);
result = write(*write_fd,string,strlen(string)); // 子进程写。
return 0;
}else {
close(*write_fd);
nbytes = read(*read_fd,readbuffer,sizeof(readbuffer)); // 父进程读
printf("receive %d data, is :%s",nbytes,readbuffer);
}
return 0;
}
管道进行写入操作时,当写入数据小于128K 时,写入是非原子的。
管道最大写入阈值 PIPE_BUF (至少是512),数值受内核版本限制。
命名管道
与普通管道方式相似。不同:
- 在文件系统中命名管道是以设备特殊文件的形式存在的
- 不同的进程可以通过命名管道共享数据。
创建FIFO
命令: mkfifo
函数 mkfifo()
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char*pathname,mode_t mode)
在FIFO 中必须用一个open()函数来显示的建立连接到管道的通道,一般来说FIFO总是处于阻塞状态的。可在open() 调用中使用O_NONBLOCK标记,关闭默认阻塞动作。

被折叠的 条评论
为什么被折叠?



