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/