我有两个C文件 fifoserver.c 和 fifoclient.c
服务器程序创建一个用于读取的FIFO,并将从命名管道接收的任何内容显示到标准输出。另一方面,客户端程序应该打开由服务器程序创建的FIFO进行写入,并将从标准输入读取的任何内容写入命名管道。
但是,我的fifoclient.c程序无法读取任何用户输入并打印出无输入。为什么呢?
这是我的代码:
fifoserver.c
//fifoserver.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, sizeof(buffer));
}
close(fd);
exit(0);
}
fifoclient.c
//fifoclient.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((n=read(fd,buffer,sizeof(buffer)))>0){
fgets(buffer, sizeof(buffer), stdin);
write(fd, buffer, strlen(buffer)+1);
}
close(fd);
exit(0);
}
要执行这两个程序,请在运行客户端程序之前在后台运行服务器程序。例如:
./fifoserver &
./fifoclient < /etc/passwd