1.管道
管道可以用来在两个进程之间传递数据,如: ps -ef | grep “bash”, 其中‘|’就是管道,其作用就是将ps 命令的结果写入管道文件,然后 grep 再从管道文件中读出该数据进行过滤。
2.有名管道
有名管道可以在任意两个进程之间通信有名管道的创建:
1>命令创建: mkfifo FIFO
2>系统调用创建
#include <sys/types.h>
#include <sys/stat.h>
//filename 是管道名 mode 是创建的文件访问权限
int mkfifo(const char *filename, mode_t mode);
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <fcntl.h>
int main()
{
int fd = open("FIFO", O_WRONLY);
assert(fd != -1);
printf("open FIFO success\n");
while(1)
{
printf("please input: ");
char buff[128] = {0};
fgets(buff, 128, stdin);
write(fd, buff, strlen(buff) - 1);
if(strncmp(buff, "end", 3) == 0)
{
break;
}
}
close(fd);
exit(0);
}
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <fcntl.h>
int main()
{
int fd = open("FIFO", O_RDONLY);
assert(fd != -1);
printf("open FIFO success\n");
while(1)
{
char buff[128] = {0};
int n = read(fd, buff, 127);
if(n <= 0 || 0 == strncmp(buff, "end", 3))
{
break;
}
printf("%s\n", buff);
}
close(fd);
exit(0);
}
3.无名管道
无名管道主要应用于父子进程间的通信
创建:
#include<unistd.h>
/*
pipe()成功返回0,失败返回-1
fds[0]是管道读端的描述符
fds[1]是管道写端的描述符
*/
int pipe(int fds[2]);
演示:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <asscrt.h>
#include <stringh>
int main()
{
int fd[2];
int res = pipe(fd);
asser(res!=-1);
pid_ t pid = fork0;
assert( pid!=-1 ); .
if(pid==0)
{
char buff[128] = {0};
read(fd[0], buff, 127);
prinf("child read: %s\n", buff);
}
else
{
write(fd[1], "hello", 5);
}
close(fd[0]);
close(fd[1);
exit(0);
}
4.管道的特点
1>无论有名还是无名,写入管道的数据都在内存中
2>管道是一种半双工通信方式(通信方式有单工、半双工、全双工)
3>有名和无名管道的区别:有名可以在任意进程间使用,而无名主要在父子进程间