【问题标题】:Why open() has no 'fd' return in linux 1.0?为什么 open() 在 linux 1.0 中没有“fd”返回?
【发布时间】:2019-07-04 18:34:20
【问题描述】:

既然'fd'没有返回,那以后怎么读/写呢?

例如:

void init(void)
{
 ....
 (void) open("/dev/tty1",O_RDWR,0);
 ....

【问题讨论】:

标签: c linux kernel driver


【解决方案1】:

open 在其中返回一个值。 The cast-to-void is used to signal the compiler that the return value is being deliberately ignored.

init 函数是当前线程准备在用户空间执行init 程序的函数。 init 将期望打开标准输入、输出和错误描述符。完整代码如下:

(void) open("/dev/tty1",O_RDWR,0);
(void) dup(0);
(void) dup(0);

没有必要将返回值存储到任何东西,因为open保证使用最低的空闲描述符,并且在进入这个函数之前进程没有使用任何描述符,因此@987654329 @ 将返回 0。返回最低免费的相同规则也适用于 dup。在这 3 次调用之后,所有描述符 0、1 和 2 共享相同的文件描述,这也意味着您可以写入标准输入并从标准错误中读取。

这或许是一个微优化,但确实没必要在open的返回值已知的情况下使用变量让编译器生成不合标准的代码——毕竟是类似的

int fd = open("/dev/tty1",O_RDWR,0);
assert(fd == 0);
(void) dup(fd);
(void) dup(fd);

In the current revision 那里 有一个断言,检查 open 没有失败:

/* Open the /dev/console on the rootfs, this should never fail */
if (ksys_open((const char __user *) "/dev/console", O_RDWR, 0) < 0)
    pr_err("Warning: unable to open an initial console.\n");

(void) ksys_dup(0);
(void) ksys_dup(0);

但是,实际的文件描述符返回值被忽略了。

【讨论】:

  • 这只是我的意见,但我想说像(void) open("/dev/tty1",O_RDWR,0); 这样假设返回值始终为零的代码是不必要的脆弱。它完全排除了失败的可能性,同时还假设代码运行的上下文永远不会改变。根据我的经验,两者都很可能被证明是错误的。
  • @AndrewHenle 是的,它可以使用if 检查返回值,如果不是 0,则内核崩溃。
猜你喜欢
  • 1970-01-01
  • 2019-09-28
  • 1970-01-01
  • 1970-01-01
  • 2014-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多