Chinaunix

标题: linux中FIFO实现一个服务器多个客户 [打印本页]

作者: _Gushi    时间: 2018-07-24 20:04
标题: linux中FIFO实现一个服务器多个客户
//server.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "my_err.h"
#include "unpipc.h"

#define SERV_FIFO "/work/test/test.serv"

int main()
{
        char buff[MAXLINE+1],fifoname[MAXLINE];

        if((mkfifo(SERV_FIFO,FILE_MODE)<0)&&(errno!=EEXIST))
          err_sys("can't create %s",SERV_FIFO);

        //open sever's well-know FIFO reading and write
        int readfifo=open(SERV_FIFO,O_RDONLY,0);
        int dummyfd=open(SERV_FIFO,O_WRONLY,0);

        //read pathname from IPC(is from client pathname) to fifoname
        ssize_t n;
        if((n=read(readfifo,fifoname,MAXLINE))==0)
                err_quit("end of file while reading pathname");
        //fifoname[n]='\0';
        
        //open write text to pathname(fifoname)
        int writefd=open(fifoname,O_WRONLY,0);
        
        //write text(from SERV_FIFO) to pathname(fifoname)
        int fd;
        if((fd=open(fifoname,O_RDONLY))<0)
        {
                int len=strlen(fifoname);
                write(writefd,fifoname,len);
                close(writefd);
        }
        else
        {
                while((n=read(fd,buff,MAXLINE))>0)
                        write(writefd,buff,n);

                close(fd);
                close(writefd);
        }
        exit(0);        
}

//client.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include "unpipc.h"
#include "my_err.h"

#define SERV_FIFO "/work/test/test.serv"

int main()
{
        char fifoname[MAXLINE],buff[MAXLINE];
        
        //read pathname
        fgets(fifoname,MAXLINE,stdin);
        size_t len=strlen(fifoname);
        if(fifoname[len]=='\n')
          len--;

        //create FIFO whie pathname
        if((mkfifo(fifoname,FILE_MODE)<0)&&(errno!=EEXIST))
          err_sys("can't create %s",fifoname);
        
        //open FIFO to server and write pathname to FIFO
        int writefifo=open(SERV_FIFO,O_WRONLY,0);
        write(writefifo,fifoname,len);

        //now open our FIFO;blocks until server opens for writing
        int readfifo=open(fifoname,O_RDONLY,0);

        //read from IPC,write to standard output
        ssize_t n;
        while((n=read(readfifo,buff,MAXLINE))>0)
          write(STDOUT_FILENO,buff,n);

        close(readfifo);
        unlink(fifoname);
        exit(0);
}
运行完./server &后,运行./client,gdb调试时总是阻塞在int readfifo=open(fifoname,O_RDONLY,0);,求指教。






欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2