管道由pipe函数创建,是进程间通信的一种方式。
#include <unistd.h>
int pipe(int fd[2]); 返回:成功时为0,出错时为-1
该函数数返回两个文件描述符:fd[0]和fd[1]。前者用于读,后者用于写。
管道的典型用途是提供两个不同进程(一个是父进程,一个是子进程)间的通信手段。 一个管道只能提供单向的数据流,当需要一个双向的数据流时,我们必须创建两个管道,每个方向一个。实际步骤如下:
1.创建管道1(fd1[0]和fd1[1])和管道2(fd2[0]和fd2[1])
2.fork
3.父进程关闭管道1的读端(fd1[0])
4.父进程关闭管道2的写端(fd2[1])
5.子进程关闭管道1的写端(fd1[1)
6.子进程关闭管道2的读端(fd2[0)
实现代码如下:
/*
* main.cpp
*
* Created on: 2013-10-26
* Author: Richard
*/
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
void client(int readfd, int writefd)
{
size_t len;
size_t n;
char buff[1024];
fgets(buff, 1024, stdin);
len = strlen(buff);
if (buff[len - 1] == '\n')
{
len--;
}
write(writefd, buff, len);
while ((n = read(readfd, buff, 1024)) > 0)
{
write(STDOUT_FILENO, buff, n);
}
}
void server(int readfd, int writefd)
{
int fd;
ssize_t n;
char buff[1025];
if ((n = read(readfd, buff, 1024)) == 0)
{
printf("End of file while reading pathname");
exit(0);
}
buff[n] = '\0';
if ((fd = open(buff, O_RDONLY)) < 0)
{
snprintf(buff + n, sizeof(buff) - n, "Cannot open, %s\n",
strerror(errno));
n = strlen(buff);
write(writefd, buff, n);
}
else
{
while ((n = read(fd, buff, 1024)) > 0)
{
write(writefd, buff, n);
}
close(fd);
}
}
int main(int argc, char **argv)
{
int pipe1[2];
int pipe2[2];
pid_t childpid;
pipe(pipe1);
pipe(pipe2);
if ((childpid = fork()) == 0)
{
close(pipe1[1]);
close(pipe2[0]);
server(pipe1[0], pipe2[1]);
exit(0);
}
close(pipe1[0]);
close(pipe2[1]);
client(pipe2[0], pipe1[1]);
waitpid(childpid, NULL, 0);
return 0;
}
main函数创建两个管道并fork一个子进程。客户作为父进程运行,服务器作为子进程运行。第一个管道用于客户向服务器发送路径名,第二个管道用于服务器向客户发送该文件的内容。