基本上我希望我的客户端程序从文件(命令行输入中指定的文件名/路径)读取数据并将该数据复制到FIFO,并且我希望我的服务器程序从FIFO中读取并打印每一行。命名PIPE(FIFO)读取文件的内容C
例如,如果我想打印/ etc/passwd文件的文本文件,我在这样的终端上运行程序的内容:
./server &
./client < /etc/passwd
然而,不是打印任何输出,它打印出只有'完成'了。 为什么?
这里是我的代码:
server.c
//server.c
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define FIFONAME "myfifo"
int main(void){
int n,fd;
char buffer[1024];
unlink(FIFONAME);
//create FIFO
if(mkfifo(FIFONAME,0666)<0){
perror("server: mkfifo");
exit(1);
}
//open FIFO for reading
if((fd = open(FIFONAME, O_RDONLY))<0){
perror("server: open");
exit(1);
}
//READ from fifo UNTIL end of tile and print
//what we get on the standard input
while((n=read(fd,buffer,sizeof(buffer)))>0){
write(1, buffer, n);
}
close(fd);
exit(0);
}
。
client.c
//client.c
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define FIFONAME "myfifo"
int main(void){
int n,fd;
char buffer[1024];
/* open, read, and display the message from the FIFO */
if((fd = open(FIFONAME, O_WRONLY))<0){
perror("client: open");
exit(1);
}
//read from standard input and copy data to the FIFO
while (fgets(buffer, sizeof(buffer), stdin) != 0){
fgets(buffer, sizeof(buffer), stdin);
write(fd, buffer, n);
}
close(fd);
exit(0);
}
您确定服务器有时间在客户端启动之前创建FIFO(这将在客户端创建一个常规文件) –
@ Jean-FrançoisFabre的确,在客户端开始之前它确实有足够的时间来创建FIFO ! – fredjohnson
你可以在服务器和客户端之间添加一个“睡眠”吗?花费不大,但值得一试。 –