管道pipe&&fifo

1.pipe

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <stdlib.h>
int main(int argc,char *argv[]){
        pid_t pid1;
        int pipefd[2];
        char buf;
        if(pipe(pipefd)==-1){
                perror("pipe");
                exit(-1);
        }


        if((pid1=fork())<0){
                perror("fork");
                exit(-1);
        }


        if(pid1==0){
                sleep(1);
                close(pipefd[1]);
                while(read(pipefd[0],&buf,1)>0)
                        write(STDOUT_FILENO,&buf,1);
                write(STDOUT_FILENO,"\n",1);
                close(pipefd[0]);
                exit(0);
        }
        else {
                close(pipefd[0]);
                write(pipefd[1],argv[1],sizeof(argv[1]));
                close(pipefd[1]);
                wait(NULL);
                exit(0);
        }
}

2.fifo

2.1 read

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>


int main(int argc,char *argv[]){
        int fd1;
        char var[10];
        remove("fifo1");
        if(mkfifo("fifo1",0666)==-1){
                perror("fifo");
                exit(-1);
        }
        if((fd1 = open("fifo1",O_RDONLY))<0){
                perror("open");
                exit(-1);
        }


        if(read(fd1,var,10)<0){
                perror("read");
                exit(-1);
        }
/*
        if(read(fd1,var,10)==0){
                printf("read ooo");
                exit(0);
        }
*/
        printf("%s\n",var);
        close(fd1);
        return 0;
}


2.2 write

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>


int main(int argc,char *argv[]){
        int fd1;
        char var[10];


        if((fd1=open("fifo1",O_WRONLY))<0){
                perror("openw");
                exit(-1);
        }


        if(write(fd1,"abc\n",4)==-1){
                perror("write");
                exit(-1);
        }


        close(fd1);
        return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值