【发布时间】:2016-08-23 18:44:55
【问题描述】:
我编写了一对简单的读写器程序。 Writer 创建/打开一个 FIFO 文件,并不断向其中写入一个字符串。读者只是在阅读它并写入标准输出。读者只这样做了 10 次,然后退出。令人惊讶的是(对我来说)作者也几乎立即退出了。它不仅超出了写作循环,而且似乎跳出了它,我可以通过在屏幕上看不到最后的“再见”来判断它。我可以接受这种行为,但我仍然不明白为什么。 有人可以与我分享他们的知识吗?
/* writer code */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
char msg [] = "Leo_Tolstoy";
size_t len = strlen("Leo_Tolstoy");
if (mkfifo ("myfifo", 0600) != 0) {
perror ("creating fifo");
}
int fd;
if ( (fd = open ("myfifo", O_WRONLY)) == -1) {
perror ("opening fifo");
exit (1);
}
while (1)
{
int r = write (fd, msg, len);
if (r == -1)
perror ("writing");
sleep(1);
}
printf ("byebye\n");
close (fd);
return 0;
}
/* reader code */
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/shm.h>
int main()
{
char buf[50];
printf ("bef opening\n");
int fd = open ("myfifo", O_RDONLY);
if (fd == -1) {
perror ("opening fifo");
exit (1);
}
printf ("bef reading\n");
int cnt=0;
while (cnt < 10)
{
int r = read (fd, buf, 50);
if (r == 0)
break;
if (r == -1)
perror ("reading");
write (1, buf, r);
cnt++;
}
// close (fd);
return 0;
}
【问题讨论】:
-
所以,C 或 C++。我会说 C,但那是你的决定。请选择 一种 语言,而不是 2 种(您的问题似乎不适用于不同的语言)。
-
没有语言 C/C++,只有两种不同的语言 C 和 C++。选择其中一个。
-
调试器说什么?
-
我选择了 C)。我没有使用调试器,很遗憾,但我不知道如何使用 gdb,而且我现在没有安装 IDE(它只是一个带有 Ubuntu 14.04 的 VM)
-
if (mkfifo ("myfifo", 0600) != 0)使用八进制值,如果相关,则为十进制 384。