管道
内核提供,单工,自同步机制(永远迁就速度慢的一方)
匿名管道
由内核维护创建,没有文件名,在文件系统上不显示,只有有亲缘关系的进程才能使用。
函数 pipe
NAME
pipe, pipe2 - create pipe
SYNOPSIS
#include <unistd.h>
int pipe(int pipefd[2]);//0端为读端 1端为写端
#define _GNU_SOURCE /* See feature_test_macros(7) */
#include <fcntl.h> /* Obtain O_* constant definitions */
#include <unistd.h>
int pipe2(int pipefd[2], int flags);
DESCRIPTION
pipe() creates a pipe, a unidirectional data channel that can be
used for interprocess communication. The array pipefd is used to
return two file descriptors referring to the ends of the pipe.
pipefd[0] refers to the read end of the pipe. pipefd[1] refers to the
write end of the pipe. Data written to the write end of the pipe is
buffered by the kernel until it is read from the read end of the pipe.
For further details, see pipe(7).
简单实例:父进程写管道 子进程读管道
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <wait.h>
#define BUFSIZE 1024
int main(){
int pd[2];
pid_t pid;
char buf[BUFSIZE];
int len;
if(pipe(pd) < 0){
perror("pipe():");
exit(1);
}
pid = fork();
if(pid < 0){
perror("fork():");
exit(1);
}
if(pid == 0){ //子进程读管道
close(pd[1]);
len = read(pd[0], buf, BUFSIZE);
write(1, buf, len);
close(pd[0]);
exit(0);
}
else{ //父进程写管道
close(pd[0]);
write(pd[1], "Hello!\n", 7);
close(pd[1]);
wait(NULL);
exit(0);
}
}
命名管道
函数:mkfifo()
NAME
mkfifo, mkfifoat - make a FIFO special file (a named pipe)
SYNOPSIS
#include <sys/types.h>
#include <sys/stat.h>
/*
pathname 管道文件名字
mode 权限
*/
int mkfifo(const char *pathname, mode_t mode);
#include <fcntl.h> /* Definition of AT_* constants */
#include <sys/stat.h>
int mkfifoat(int dirfd, const char *pathname, mode_t mode);