两个进程间的读写功能-cp(随记)
(有问题请随时指正)
有名管道特点:
- 可以使不相干进程进行通信。
- 有名管道可以通过路径名指出,在文件系统中可见,但内容存放在内存中。
- 文件IO操作有名管道
- 遵循先进先出
- 不支持lseek()操作。
注意事项: - 只写方式,写阻塞,一直到另一个进程把读打开
- 只读方式,读阻塞,一直到另一个进程把写打开
- 可读可写,若管道中无数据,读阻塞。
有名管道和无名管道比较
fiforead.c
//两个进程间实现文件复制,第一部分读
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
int main()
{
//int fifo;
if(mkfifo(“./34”,0666) < 0) //创建有名管道,管道名字为34,给到权限0666,并判断是否成功创建;
{
if (errno == EEXIST)//判断管道是否已经存在,如存在打印hear
printf(“hear\n”);
else//如果不存在判断错误原因
{
perror(“mkfifo err\n”);
return -1;
}
}
printf(“mkfifo duccess\n”);
int myOpen1,myOpen2;
char buf[64];
ssize_t s;
myOpen1 = open(“./34”,O_WRONLY);//管道 ,只写权限
myOpen2 = open(“./pipe.c”,O_RDONLY);//本地文件 只读权限
while(1)
{
s = read(myOpen2,buf,64);//读本地文件内容准备写进管道
if(s == 0) // 当读到最后退出
break;
write(myOpen1,buf,s);//往管道写读到的本地文件的内容
}
close(myOpen1);//关闭
close(myOpen2);
return 0;
}
fifowrite.c
//有名管道第二部分,写
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
int main()
{
if(mkfifo(“./34”,0666) < 0)//创建有名管道,管道名字为34,给到权限0666,并判断是否成功创建;
{
if (errno == EEXIST)//判断管道是否已经存在,如存在打印hear
printf(“hear\n”);
else//如果不存在判断错误原因
{
perror(“mkfifo err\n”);
return -1;
}
}
printf(“mkfifo success\n”);
int op1,op2;
char buf[64];
ssize_t s;
op1 = open(“./34”,O_RDONLY);//管道,只写权限
op2 = open(“./l.c”,O_WRONLY|O_TRUNC|O_CREAT,0666);//只写|如果存在清空|不存在创建权限0666
while(1)
{
s = read(op1,buf,64);//读管道里面的内容
if(s == 0)
break;
write(op2,buf,s); //往了.c文件里面写读到的内容
}
close(op1);//关闭
close(op2);
return 0;
}