且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Linux - 为什么自定义系统调用不能正确处理负数?

更新时间:2022-11-19 08:35:28

如果系统调用返回负值,则将其视为错误,并在libc中调用特殊错误处理代码。即,返回值被否定并移入 errno 全局变量,系统调用的返回值变为 -1

If a system call returns a negative value it's treated as an error, and special error handling code is invoked in libc. Namely, the return value is negated and moved into the errno global variable, and the return value of the system call becomes -1.

实际上,在阅读本文时我发现在Linux上,仅将-4095到-1的值视为错误,但这既不便于携带,也不是有用的您的函数可以处理任何可能的值。

Actually, while reading about this I discovered that on Linux, only values from -4095 to -1 are treated as errors, but this is neither portable, nor helpful if you want your function to work on any possible values.

简而言之,您无法安全地使用系统调用的返回值来返回可能为负值的值。通常的惯例是传递指向目标变量的指针以保存结果,并保留成功/失败的返回码。请注意,使用系统调用执行此操作时,您将使用来自内核空间的用户空间指针,因此写入结果需要copy_to_user

In short, you can't safely use the return value of a syscall to return a value that might be negative. The usual convention would be to pass a pointer to a destination variable to hold the result, and reserve the return code for success/failure. Note that when doing this with a syscall you will be working with a user-space pointer from kernel-space, so copy_to_user will be necessary to write the result.