int pipe(int pipefd[2]);
//匿名管道
int main()
{
int fds[2];
int len;
char buf[100]={};
if(pipe(fds)==-1) //创建管道
perror("pipe"),exit(1);
while(fgets(buf,100,stdin))
{
len = strlen(buf);
if(write(fds[1],buf,len)==-1) //把内容写进管道
perror("write"),exit(1);
memset(buf,0x00,sizeof(char)*100);
if(read(fds[0],buf,len)==-1) //从管道里面读取内容到数组中
perror("read"),exit(1);
if(write(1,buf,len)==-1) //把从管道里读出的内容写到标准输出
perror("write"),exit(1);
}
return 0;
}
//父子进程通信
int main()
{
char buf[1024]="change world!\n";
int fds[2];
if(pipe(fds)==-1)
perror("pipe"),exit(1);
pid_t pid = fork(); //创建匿名管道
if(pid==0)
{
close(fds[0]); //关闭管道读描述符
if(write(fds[1],buf,1024)==-1) //写进管道
perror("write"),exit(1);
close(fds[1]);
exit(1);
}
else
{
memset(buf,0x00,1024);
close(fds[1]); //关闭管道写描述符
if(read(fds[0],buf,1024)==-1) //从管道读内容
perror("read"),exit(1);
if(write(1,buf,1024)==-1)
perror("write"),exit(1);
close(fds[0]);
exit(1);
}
return 0;
}
当没有数据可读时
当管道满的时候
我们刚刚可以用匿名管道在父子进程之间通信,那如果是两个不想光的进程之间该如何通信呢?
int main()
{
mkfifo("my.p",0644);
return 0;
}
#include
#include
#include
#include
#include
#include
int main()
{
mkfifo("my.p",0664);
int outfd = open("my.p",O_WRONLY);
if(outfd==-1)
perror("open my.txt"),exit(1);
char buf[1024]={};
int n = 0;
while(fgets(buf,1024,stdin))
{
write(outfd,buf,1024);
memset(buf,0x00,1024);
}
close(outfd);
从管道中读内容,标准输出输出
#include
#include
#include
#include
#include
#include
int main()
{
int infd = open("my.p",O_RDONLY);
if(infd==-1)
perror("open my.p"),exit(1);
char buf[1024]={};
int n = 0;
while((n = read(infd,buf,1024))>0)
{
write(1,buf,n);
memset(buf,0x00,1024);
}
close(infd);
unlink("my.p"); //删除管道
return 0;
}