我必须实现一个“打印服务器”。我有 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 循环。如果我从客户端发送消息,则会打印第一条消息,但会忽略以下消息。
有人可以帮我解决我的问题吗?
谢谢
帕特里克