c - 为什么 file_operations 中的 unlocked_ioctl 返回 long,而 sys/ioctl.h 中的 ioctl() 返回 int?

标签 c unix linux-kernel linux-device-driver ioctl

struct file_operations中的unlocked_ioctl的签名是

long (*unlocked_ioctl) (struct file *, unsigned int, unsigned long);

而 man 2 ioctl 说 ioctl(2) 的签名是:

int ioctl(int d, int request, ...);

我知道参数是如何在内核内部被破坏的,但是为什么内核空间的返回类型是long,而用户空间的返回类型是int?当我想返回一个负值作为错误时,这会产生一个问题:由于二补码编码,我返回的所有负值都会变成 -1。

最佳答案

如果从 file_operations 函数返回负值,内核会将其解释为负 errno(即错误返回)。然后,用户代码获取 -1 作为返回值,并将 errno 设置为原始返回值的负值。这与二进制补码无关。

man 2 intro 、“系统调用简介”:

On error, most system calls return a negative error number (i.e., the negated value of one of the constants described in errno(3)). The C library wrapper hides this detail from the caller: when a system call returns a negative value, the wrapper copies the absolute value into the errno variable, and returns -1 as the return value of the wrapper.

例如,如果您从 unlocked_ioctl 返回 -ENOTTY,则用户程序会从 ioctl 获取 -1 且 errno = ENOTTY.

关于c - 为什么 file_operations 中的 unlocked_ioctl 返回 long,而 sys/ioctl.h 中的 ioctl() 返回 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12127684/

相关文章:

c - getc 在文件结束后应该停止时正在打印垃圾

c++ - Typedef-name 与 C++ 中的 struct 标记冲突

unix - 管道到 UNIX 日期函数

linux - 为什么计划策略和参数的设置在我的程序 - pthread Linux 中失败?

c - 预期声明说明符错误,声明外部堆栈时

c - 从字符串数组中删除字符串 (C)

unix - 目录执行和文件读取权限的区别

linux - 如何对已在后台运行的进程使用 nohup

c - 使用 PF_PACKET 类型的套接字时,PACKET_ADD_MEMBERSHIP 的作用是什么?

linux - 修改哪个文件以永久更改/proc/sys 中的值