管道和FIFO例子

管道:

#include "unpipc.h"
int
main(int argc, char **argv)
{
        int fd[2];
        Pipe(fd);
        pid_t childpid;
        int n;
        if((childpid=Fork())==0){
                Close(fd[0]);
                char buf[2000];
                Fgets(buf,2000,stdin);
                Write(fd[1],buf,strlen(buf));
                exit(0);
        }
        Close(fd[1]);
        char buf[2000];
        if((n=Read(fd[0],buf,2000))<0)
                err_sys("error");
        Fputs(buf,stdout);
        waitpid(childpid,NULL,0);
        exit(0);
}
image.png

FIFO:

#include "unpipc.h"
#define FIFO_SERV "/tmp/fifo.lala"

int main(int argc,char **argv)
{
        if(mkfifo(FIFO_SERV,FILE_MODE)<0&&(errno!=EEXIST))
                err_sys("error");
        int writefd;
        writefd=Open(FIFO_SERV,O_WRONLY,0);
        char buf[2000];
        Fgets(buf,2000,stdin);
        Write(writefd,buf,strlen(buf));
        Close(writefd);
        exit(0);
}
#include "unpipc.h"
#define FIFO_SERV "/tmp/fifo.lala"
int
main(int argc, char **argv)
{
        if((mkfifo(FIFO_SERV,FILE_MODE))<0&&(errno!=EEXIST))
                err_sys("error");
        int readfd;
        readfd=Open(FIFO_SERV,O_RDONLY,0);
        char buf[2000];
        int n;
        if((n=Read(readfd,buf,2000))<0)
                err_sys("read error");
        Fputs(buf,stdout);
        Close(readfd);
        exit(0);
}
image.png

你可能感兴趣的:(管道和FIFO例子)