主要内容:匿名管道,命令管道。(pipe, popen, mkfifo等函数)
管道简介:
管道是进程之间通信的一种方式,就相当于是两个进程之间有一条地道,可以通过地道来传递信息;
管道位于进程的地址空间之外;管道分为匿名管道和命名管道两种;匿名管道是由pipe来创建的,命名管道是由mkfifo来创建的;
#include <unistd.h>
int pipe(int pipefd[2]);
返回两个描述符:pipefd[0]是管道的读端,pipefd[1]是管道的写端;
下面是一个父子进程利用管道通信的实例:
main函数创建两个管道,并用fork生成一个子进程,客户端作为父进程运行,服务器则作为子进程运行。第一个管道用于从客户向服务器发送路径名, 第二个管道用于从服务器向客户发送该文件的内容。
客户端写pipe1[1]-----pipe1[0]服务器读
服务器写pipe2[1]-----pipe2[0]客户端读
客户端写pipe1[1]-----pipe1[0]服务器读
服务器写pipe2[1]-----pipe2[0]客户端读
/*************************************************************************
> File Name: mainpipe.c
> Author:
> Mail:
> Created Time: 2016年04月20日 星期三 22时25分15秒
************************************************************************/
/*
* main函数创建两个管道,并用fork生成一个子进程
* 客户端作为父进程运行,服务器则作为子进程运行
* 第一个管道用于从客户向服务器发送路径名
* 第二个管道用于从服务器向客户发送该文件的内容
*
* cin --客户端写pipe1[1]-----pipe1[0]服务器读
* 服务器写pipe2[1]-----pipe2[0]客户端读
*/
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
//服务器从rfd中读取文件的名字,向wfd中写入文件的内容
void server(int rfd, int wfd)
{
char fileName[1024];
char fileContent[2048];
memset(fileName, 0, 1024);
memset(fileContent, 0, 2048);
//从rfd中读取文件的名字,
int n = read(rfd, fileName, 1024);
fileName[n] = 0;
printf("server receive the file name is %s\n", fileName);
int filefd = open(fileName, O_RDONLY);//打开文件
if(filefd < 0){
printf("open error\n");
return;
}
else{//读取文件的内容,并写入到wfd中
//读取文件的内容到fileContent中
int num = 0;
while((num = read(filefd, fileContent, 2048)) > 0){
printf("server read the fileContent is: %s", fileContent);
//将fileContent中的内容写入到wfd中
write(wfd, fileContent, num);
}
}
close(filefd);
close(rfd);
close(wfd);
}
//客户端从rfd中读取文件的内容,向wfd中写入文件的名字
void client(int rfd, int wfd)
{
char fileName[1024];
char fileContent[2048];
memset(fileName, 0, 1024);
memset(fileContent, 0, 2048);
printf("输入文件名字:");
//从标准输入输入文件的名字
fgets(fileName, 1024, stdin);
int len = strlen(fileName);
if(fileName[len-1] =