免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 7070 | 回复: 0
打印 上一主题 下一主题

[Linux] linux下用FIFO实现一个服务器多个客户 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2018-07-24 19:09 |只看该作者 |倒序浏览
//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);,求指教。

您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP