【发布时间】:2013-04-11 19:27:26
【问题描述】:
我有两个程序,服务器和客户端。服务器应该读取一个文件,然后通过命名管道将其内容发送到客户端。但是我的服务器只从文件中读取两个字符,然后退出。这段代码有什么问题?
server.c:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#define FIFO_NAME "american_maid"
int main(void)
{
char line[300];
int num, fd;
FILE *fp;
fp = fopen("out.txt","r");
mknod(FIFO_NAME, S_IFIFO | 0666, 0);
printf("waiting for readers...\n");
fd = open(FIFO_NAME, O_WRONLY);
printf("got a reader--type some stuff\n");
while (fgets(line, sizeof(line), fp)) {
if ((num = write(fd, line, strlen(line))) == -1)
perror("write");
else
printf("speak: wrote %d bytes\n", num);
}
fclose(fp);
return 0;
}
client.c:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#define FIFO_NAME "american_maid"
int main(void)
{
char s[300];
int num, fd;
mknod(FIFO_NAME, S_IFIFO | 0666, 0);
printf("waiting for writers...\n");
fd = open(FIFO_NAME, O_RDONLY);
printf("got a writer\n");
do {
if ((num = read(fd, s, 300)) == -1)
perror("read");
else {
s[num] = '\0';
printf("tick: read %d bytes: \"%s\"\n", num, s);
}
} while (num > 0);
return 0;
}
【问题讨论】:
-
如果读取 300 字节,客户端会在缓冲区 's' 的末尾写入一个字符。这不是你描述的问题。
-
抱歉我的建议(不要在客户端代码中创建文件)没有帮助。我已删除答案,以便您获得更多关注。
-
两个程序的“当前”文件夹是否相同? FIFO文件名上没有路径(例如
/tmp/american_maid) -
不,它们在同一个目录中(客户端、服务器和 American_maid fifo)
-
检查您的
open()呼叫是否有效。请注意,如果您在客户端读取 300 个字节,则写入s[num]会超出数组末尾;它可能会弄乱读取的数据字节数。
标签: c client-server named-pipes fifo mkfifo