首先:
一、无名管道pipe:
1,没有名字的
2,半双工 //读写不能同时进行
3,通过直系亲属访问继承
4,管道默认会阻塞
5,不能用lseek定位
6,操作没有原子性
示例代码 :
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
void signal_hand(int signum)
{
printf("recv SIGPIPE\n");
}
int main(void)
{
char buffer[100];
int retval;
int pipe_fd[2];
pipe(pipe_fd);
pid_t pid;
signal(SIGPIPE, signal_hand);
pid = fork();
if(pid == 0)
{
close(pipe_fd[0]);
pause();
retval = read(pipe_fd[0], buffer, sizeof(buffer));
if(retval == -1)
{
perror("read pipe failed\n");
exit(EXIT_FAILURE);
}
printf("buffer=%s\n", buffer);
exit(EXIT_SUCCESS);
}
close(pipe_fd[0]);
while(1)
{
fgets(buffer, sizeof(buffer), stdin);
retval = write(pipe_fd[1], buffer, strlen(buffer));
if(retval == -1)
{
perror("write error\n");
}
}
return 0;
}
二、有名管道fifo:(文件)
1,有名字
2,全双工 //可以同时进行读写
3,可以没有亲属关系
4,管道默认会阻塞
5,不能用lseek定位
6,操作有原子性 // 当有一个进程对其进行操作是其他进程不能对其操作
示例代码:
有名管道要先创建一个管道文件(ps:window下不支持管道文件,所以不要在ubuntu的共享目录下创建)
fifo写端.c
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <sys/stat.h>
#include <fcntl.h>
#define PATH "/home/myfifo"
int main(void)
{
int retval; //用来存放 mkfifo函数的返回值 用来判断 是否成功
if(access(PATH, F_OK)) // F_OK 判断文件是否存在
{
retval = mkfifo(PATH, 0665);
if(retval == -1)
{
perror("creat fifo error\n");
return -1;
}
printf("create success\n");
}
int fifo_fd; //存放open函数的返回值
fifo_fd = open(PATH, O_RDWR);
if(fifo_fd == -1)
{
perror("open fifo error\n");
return -1;
}
char buffer[100]; //设置管道一次可以写的大小
bzero(buffer, sizeof(buffer));
while(1)
{
fgets(buffer, sizeof(buffer), stdin); //从屏幕上获取buffer大小的数据存入buffer中
write(fifo_fd, buffer, strlen(buffer));
}
close(fifo_fd);
return 0;
}
fifo读端.c
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <sys/stat.h>
#include <fcntl.h>
#define PATH "/home/gecmyfifo"
int main(void)
{
int retval; //用来存放 mkfifo函数的返回值 用来判断 是否成功
if(access(PATH, F_OK)) // F_OK 判断文件是否存在
{
retval = mkfifo(PATH, 0665);
if(retval == -1)
{
perror("creat fifo error\n");
return -1;
}
printf("create success\n");
}
int fifo_fd; //存放open函数的返回值
fifo_fd = open(PATH, O_RDWR);
if(fifo_fd == -1)
{
perror("open fifo error\n");
return -1;
}
char buffer[100]; //设置管道一次可以写的大小
bzero(buffer, sizeof(buffer));
while(1)
{
fgets(buffer, sizeof(buffer), stdin); //从屏幕上获取buffer大小的数据存入buffer中
write(fifo_fd, buffer, strlen(buffer));
}
close(fifo_fd);
return 0;
}