gpt4 book ai didi

c - 从命名管道读取

转载 作者:IT王子 更新时间:2023-10-29 00:35:18 26 4
gpt4 key购买 nike

我必须实现一个“打印服务器”。我有 1 个客户端文件和 1 个服务器文件:

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

int get_line( char *dest, int size );

#define MAX 1024

void main ()
{
char const *pipe = "printservers";
char buffer[MAX];
int fd;

get_line( buffer, MAX );

if( mkfifo( pipe, 0666 ) < 0 )
{
printf( "Cannot create a pipe\n" );
exit( EXIT_FAILURE );
}

fd = open( pipe, O_WRONLY );

write( fd, buffer, MAX );

close( fd );

//unlink( pipe );

}

int get_line( char *dest, int size )
{
int c, i;
for( i = 0; i < size - 1 && ( c = getchar() ) != EOF && c != '\n'; ++i )
dest[i] = c;
if( c == '\n' )
{
dest[i] = c;
++i;
}
dest[i] = '\0';
return i;
}

这是客户端,它从标准输入中读取一行并写入一个名为打印服务器的命名管道。这按预期工作。

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

#define MAX_BUF 1024
#define MAX_PID 8

int main()
{
int fd;
char * myfifo = "printservers";
char buf[MAX_BUF];

/* open, read, and display the message from the FIFO */
fd = open( myfifo, O_RDONLY );
while( 1 )
{
if( read( fd, buf, MAX_BUF ) > 0 )
printf("Received: %s\n", buf);
}
close(fd);

return 0;
}

这是从管道读取的服务器。但它不适用于 while 循环。如果我从客户端发送消息,则会打印第一条消息,但会忽略以下消息。有人可以帮我解决我的问题吗?谢谢帕特里克

最佳答案

服务器的 while 循环中存在编码错误 - 即使出现错误或服务器在 FIFO 上接收到 eof,服务器也永远不会退出循环。应该改成这样:

while(1)
{
if((bytesread = read( fd, buf, MAX_BUF - 1)) > 0)
{
buf[bytesread] = '\0';
printf("Received: %s\n", buf);
}
else
break;
}

您的另一个问题是您的客户发送了一行,然后关闭了 FIFO。服务器读取直到 EOF。所以它将读取单行,然后由于客户端关闭而命中 EOF。这是完全正常的。

当您希望您的服务器为多个客户端提供服务时,就会出现问题。在那种情况下,您不想在每个客户都结束阅读后就停止阅读。语义是这样的,即服务器只会在最后一个所有 客户端关闭后看到 EOF。因此,容纳服务器处理多个客户端的一种简单方法是将服务器端 FIFO 打开为读/写。然后总会有一个“写入器”,即服务器本身,FIFO 的写入端打开。这将阻止服务器看到 EOF,直到您决定将其关闭。

第二个问题是你需要循环读写。您保证可以在一个电话中完成您的全部数据请求。

此外,让客户端创建服务器读取的 FIFO 是一种奇怪的方法。通常,您希望服务器创建一个客户端连接到的已知 FIFO。

关于c - 从命名管道读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23498654/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com