linux---基于命名管道实现的服务器客户端

前两天学习了命名管道,今天就基于命名管道来实现一个简单的服务器客户端。

服务器端的实现思路

1. 首先创建一个命名管道
2. 从这个命名管道中读数据
3. 将读到的数据打印在标准输出上

具体代码

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

int main()
{
    if(mkfifo("mypipe",0644) < 0)
    {
        perror("mkpipe");
    }

    int rfd = open("mypipe",O_RDONLY);
    if(rfd < 0)
        perror("open");

    char buf[1024] = {0};
    while(1)
    {
        printf("please wait...\n");
        ssize_t size = read(rfd, buf, sizeof(buf) - 1);
        if(size < 0)
            perror("read");
        else if(size == 0)
            printf("client quit!\n");
        else
            printf("client say: %s\n",buf);
    }
    close(rfd);
    return 0;
}

客户端的实现思路

1. 打开命名管道
2. 向命名管道中写数据

具体实现

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
int main()
{
    int wfd = open("mypipe",O_WRONLY);
    if(wfd < 0)
        perror("open");

    char buf[1024] = {0};
    while(1)
    {
        printf("please enter: ");
        fflush(stdout);
        ssize_t size = read(0,buf,sizeof(buf)-1);
        if(size <= 0)
            perror("read");
        else
            write(wfd, buf, strlen(buf));
    }
    close(wfd);
    return 0;
}

   在写这次的代码时,需要一次编译两个 .c 文件,之前写的makefile是只能编译一个文件的,所以,就学习了一次可以编译多个源文件的makefile的写法。

.PHONY:all
all:server client

server:server.c
    gcc server.c -o server

client:client.c
    gcc client.c -o client

.PHONY:clean
clean:
    rm -rf server client mypipe

猜你喜欢

转载自blog.csdn.net/weixin_40331034/article/details/81109932