赞
踩
我们知道进程之间都是相互独立的,任何一个进程的全局变量在另一个进程中是看不到的,如果进程之间需要交换数据就要通过内核。进程间通信(InterProcess Communication)的本质就是让两个进程看到共同的资源。
我们把一个进程连接到另一个进程的一个数据流称之为管道,是Unix中最古老的进程间通信形式。我们可以分为匿名管道和命名管道。
#include <unisted>
int pipe(int fd[2]);
功能:创建一个匿名管道
参数:fd文件描述符数组,其中fd[0]表示读,fd[1]表示写
返回值:成功返回0,失败返回错误代码
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
int main()
{
int fd[2]={0};
if(pipe(fd)==-1)
{
perror("pipe");
return 1;
}
pid_t pid;
pid=fork();
if(pid==-1)
{
perror("fork");
return 2;
}
if(pid==0)
{
//child
close(fd[0]);
int a=5;
char *buf="Hello, I am your child";
while(a--)
{
write(fd[1], buf, strlen(buf));
sleep(1);
}
}
else
{
//Parent
close(fd[1]);
while(1)
{
char buf[1024]={0};
ssize_t s = read(fd[0], buf, sizeof(buf)-1);
buf[s]=0;
if(s>0)
{
printf("Parent: %s\n", buf);
}
else if(s==0)
{
printf("quit\n");
break;
}else
{
perror("read");
return 3;
}
}
}
return 0;
}

如果写端的文件描述符关闭,那么读端一直读到文件结尾返回0;
如果写端的文件描述符没有关闭并且写端不写数据,那么读端读完一直等待;
如果写端一直写数据,读端不读,那么写端写满一直等待直到开始读数据;
如果写端一直写数据,读端不读并且关闭文件描述符,那么系统会结束掉写的进程。
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);
功能:创建命名管道
参数:pathname表示管道文件路径,mode表示文件权限
返回值:成功返回0,失败返回-1,错误原因存于errno中
client.c
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<string.h>
int main()
{
int fd = open("mypipe", O_WRONLY);
if(fd < 0)
{
perror("open");
return 1;
}
char buf[1024] = {0};
while(1)
{
printf("Please Enter # ");
fflush(stdout);
ssize_t s = read(0, buf, sizeof(buf)-1);
if(s > 0)
{
buf[s] = 0;
write(fd, buf, strlen(buf));
}
else if(s == 0)
{
printf("read finish");
return 0;
}
else
{
perror("read");
return 2;
}
}
close(fd);
return 0;
}

server.c
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
int main()
{
umask(0);
if(mkfifo("mypipe", 0644) < 0)
{
perror("mkfifo");
return 1;
}
int fd = open("mypipe", O_RDONLY);
if(fd < 0)
{
perror("open");
return 2;
}
char buf[1024] = {0};
while(1)
{
printf("Please wait...\n");
ssize_t s = read(fd, buf, sizeof(buf)-1);
if(s < 0)
{
perror("read");
return 3;
}
else if(s == 0)
{
printf("client is quit\n");
return 0;
}
else
{
buf[s-1] = 0;//为了去掉输入时的换行符,所以才s-1
printf("client says # %s\n", buf);
}
}
close(fd);
return 0;
}

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。