1、无名管道
关键函数
pipe();
write();
read();
close();
代码
#include<unistd.h>
#include<stdio.h>
int main(void) {
int fd[2];//定义管道
pipe(fd);//创建管道,失败返回-1
pid_t pid = fork();//返回值为进程pid,子进程返回0,失败返回-1
if (pid == 0) {
//子进程读
close(fd[1]);//子进程关闭写管道
char line[100];//定义缓冲区
int n = read(fd[0], line, 100);//读数据,阻塞IO模型,返回读取长度
printf("%d %s\n",n, line);
}
else {
//父进程写
close(fd[0]);//父进程关闭读管道
write(fd[1], "Hello!", 6);//写数据,失败返回-1
}
getchar();
return 0;
}
2、有名管道(FIFO)
关键函数
mkfifo();
open();
write();
read();
close();
代码
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#define FD "/tmp/fifo" //有名管道利用的是文件
int main(void) {
unlink(FD);//删除已有的fifo,否则文件存在时会创建失败
if(mkfifo(FD, 0777)==-1)//创建FIFO,0777是八进制的linux权限,失败返回-1
{ }
pid_t pid = fork();
if (pid == 0) {
//子进程读
int readfd = open(FD, O_RDONLY);//打开读FIFO
char line[100];//创建缓冲区
int n = read(readfd, line, 100);//读管道
printf("%d %s\n", n, line);
close(readfd);
}
else {
//父进程写
int writefd = open(FD, O_WRONLY);//打开写FIFO
sleep(1);
write(writefd, "Hello?", 6);//写管道
close(writefd);
}
getchar();
return 0;
}