微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何为每个客户端创建唯一的命名管道

如何解决如何为每个客户端创建唯一的命名管道

我有一个典型的客户端-服务器架构,其中服务器不断从管道中读取数据以查看是否有任何客户端发送了某些内容。通常所做的是还有一个命名管道,以便服务器也可以向客户端发送它需要的任何内容

我遇到的问题是我需要根据我的需要向特定客户发送特定消息。例如,目前,对于客户端 A 和客户端 B,如果客户端 A 通过管道发送带有“进程”的消息,我需要服务器向客户端 A 发送回带有“OK”的回复,但会发生什么一个随机的人得到它(不太确定这里发生了什么,但我假设一旦客户端读取管道中的内容,另一个将无法再读取它)。

如何为每个客户端创建命名管道,以便服务器可以向特定客户端发送特定消息?以下是我拥有的代码

客户端.c


#define FIFO_FILE_1  "../tmp/fifo"
#define FIFO_FILE_2  "../tmp/fifo2"

int main(int argc,char *argv[]){

    /*if(mkfifo("fif",0666) < 0){
        perror("mkfifo");
    }*/

    int client_to_server; 
    int server_to_client;

    if((client_to_server = open(FIFO_FILE_1,O_WRONLY))<0){
        perror("open fifo");
        exit(1);
    }
    
    if((server_to_client = open(FIFO_FILE_2,O_RDONLY))<0){
        perror("open fifo");
        exit(1);
    }

    if(argc>2){
      write(client_to_server,"process\n",9);
    }

    int bytes_read = 0;
    char buf[1024]; 

    while(1){
        while((bytes_read = read(server_to_client,buf,1024)) > 0){
            write(1,"Received",7);
        }
    }

    close(client_to_server);
    close(server_to_client);
    unlink(FIFO_FILE_1);
    unlink(FIFO_FILE_2);

    return 0;
}

Server.c

#define FIFO_FILE_1  "../tmp/fifo"
#define FIFO_FILE_2  "../tmp/fifo2"

int main(int argc,char *argv[]){

    // Create named pipes
    if(mkfifo(FIFO_FILE_1,0666) < 0){
        perror("mkfifo");
    }
    if(mkfifo(FIFO_FILE_2,0666) < 0){
        perror("mkfifo");
    }

    int client_to_server; 
    int server_to_client;

    if((client_to_server = open(FIFO_FILE_1,O_RDONLY))<0){
        perror("open fifo");
        exit(1);
    }
    
    if((server_to_client = open(FIFO_FILE_2,O_WRONLY))<0){
        perror("open fifo");
        exit(1);
    }

    char buf[1024];  
    char bufaux[1024]; 

    while(1){
        int n = readCommand(client_to_server,buf); //Just reads until \n,shouldn't matter for the problem

        if (n<=0)
            continue;

        strcpy(bufaux,buf);

        char * token = first_arg(bufaux); //Returns the token until it hits a space,in this case it will return "process".

        if(strcmp(token,"process")==0){
            write(server_to_client,"OK",3);              
    }

    close(client_to_server);
    close(server_to_client);
    unlink(FIFO_FILE_1);
    unlink(FIFO_FILE_2);
    
    return 0;
}

有一些未显示的附加函数,它们只是用于解析来自客户端的管道中的任何内容。假设 strcmp(token,"process")==0 永远为真。

我将如何以及何时为每个客户端创建管道?我的想法是在客户端发送第一条消息时发送某种标识符,然后将其用于向同一个客户端写入消息。

显然问题要复杂得多,内存中有数据将被发送到每个特定的客户端,但作为一个例子,考虑我只需要发送一个“OK”。另外,我不能使用套接字。

解决方法

解决问题的一个简单方法是让客户端为返回消息创建管道。

您可以使用进程的 PID 作为名称的一部分,使其在每个进程中都是唯一的。

然后在客户端与服务器的通信中,它始终包含 PID,因此服务器知道将响应写入哪个管道。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。