【问题标题】:mknod() not creating named pipemknod() 没有创建命名管道
【发布时间】:2015-07-16 16:41:55
【问题描述】:

我正在尝试使用 mknod() 命令创建一个 FIFO 命名管道:

int main() {
char* file="pipe.txt";
int state;
state = mknod(file, S_IFIFO & 0777, 0);
printf("%d",state);
return 0;
}

但该文件未在我的当前目录中创建。我尝试通过 ls -l 列出它。状态返回 -1。

我在这里和其他网站上发现了类似的问题,并且我尝试了大多数建议的解决方案:

int main() {
char* file="pipe.txt";
int state;
unlink(file);
state = mknod(file, S_IFIFO & 0777, 0);
printf("%d",state);
return 0;
}

但这并没有什么不同,错误仍然存​​在。我在这里做错了什么还是有某种系统干预导致了这个问题?

帮助..提前致谢

【问题讨论】:

  • 你不能只是printf(state)stateint。你需要printf("%d\n", state)
  • 哦,是的...只是打字错误。谢谢

标签: linux system-calls unlink mknod


【解决方案1】:

您正在使用& 而不是| 来设置文件类型。来自文档:

path 的文件类型被 OR'ed 到 mode 参数中,并且 应用程序应选择以下符号之一 常量...

试试这个:

state = mknod(file, S_IFIFO | 0777, 0);

因为这行得通:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>


int main() {
    char* file="pipe.txt";
    int state;
    unlink(file);
    state = mknod(file, S_IFIFO | 0777, 0);
    printf("state %d\n", state);
    return 0;
}

编译:

gcc -o fifo fifo.c

运行它:

$ strace -e trace=mknod ./fifo
mknod("pipe.txt", S_IFIFO|0777)         = 0
state 0
+++ exited with 0 +++

查看结果:

$ ls -l pipe.txt
prwxrwxr-x. 1 lars lars 0 Jul 16 12:54 pipe.txt

【讨论】:

  • 不清楚您为什么将其更改为根据文档明显不正确的内容。将值与模式进行与运算只会得到0,这将创建一个没有权限的普通文件。
  • 我已经用我在系统上看到的行为更新了这个答案。
  • 嘿!那行得通。非常感谢.. 但是我想知道为什么我的程序无法运行:(.. 程序需要上述所有头文件吗??
  • 我刚刚使用了#include 的手册页,用于mknod 说要使用。这似乎是最好的做法。如果我删除除#include &lt;fcntl.h&gt; 以外的所有内容,它似乎仍然有效,尽管当然有一些警告。
  • 我明白了.. 好的。感谢您的帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-25
  • 1970-01-01
  • 2013-09-29
  • 2014-12-21
  • 2018-10-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多