我有一个简单的程序
int main () {
int fd;
int i, rc;
i = 0;
rc = mkfifo ("fff", 0);
fd = open ("fff", O_WRONLY);
fprintf(stdout,"open fifo fff succeeded\n"); fflush (stdout);
while (i<8)
{
rc = write (fd, "abcdefg", 8);
fprintf(stdout,"write to 'fff' returned with rc=%d\n",rc); fflush (stdout);
i++;
}
close (fd);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我在 Unbuntu 16.04、Linux myserv 4.4.0-81-generic #104-Ubuntu SMP 上运行它,我得到以下信息:
open fifo fff succeeded
write to 'fff' returned with rc=-1
write to 'fff' returned with rc=-1
write to 'fff' returned with rc=-1
write to 'fff' returned with rc=-1
write to 'fff' returned with rc=-1
write to 'fff' returned with rc=-1
write to 'fff' returned with rc=-1
write to 'fff' returned with rc=-1
Run Code Online (Sandbox Code Playgroud)
它显示打开和写入都是非阻塞的,没有任何进程打开读取它。根据Linux手册页,
. . . 但是,它必须在两端同时打开,然后才能对其进行任何输入或输出操作。打开 FIFO 以正常读取会阻塞,直到某个其他进程打开相同的 FIFO 进行写入,反之亦然。
好像我遇到了矛盾。有什么我错过的吗?期待对此的解释。此外,对 FIFO 实施“阻塞写入”的任何建议?
规则#1:阅读手册页了解你所做的一切。
规则#2:如有疑问,请执行ls -la。
规则#3:调试程序时,打印所有变量。
规则#3a:不要在没有先确认某件事是否真的成功之前就宣布它已经成功。
的第二个参数mkfifo是mode。您正在创建一个模式(权限)为 0 的 FIFO;即, p---------。因此,open与一个EACCESS错误而失败,并返回-1了fd。写入文件描述符-1失败并出现 EINVAL 错误。