Article Title: about pointers and error values in the Linux operating system kernel. Linux is a technology channel of the IT lab in China. Includes basic categories such as desktop applications, Linux system management, kernel research, embedded systems, and open source.
We often see ERR_PTR, IS_ERR, and PTR_ERR inline functions in kernel code and drivers.
Many kernel functions need to return a pointer, but the function call may fail. in this case, we usually return a NULL pointer, it is like the return value of malloc or kmalloc when the specified space application is not obtained. However, sometimes we want to know the cause of function failure, but returning NULL is not enough information. Therefore, some functions return an actual error code to handle the cause of the error. Many kernel interfaces return error messages by coding error values to a pointer value. When processing such a function, it cannot be compared with NULL to determine whether the call is successful. To facilitate the use of such interfaces, the 2.6 kernel implements three inline functions in linux/err. h:
inline void *ERR_PTR(long error){return (void *) error;}
|
A pointer-type function can return an error value. The error here is the normal negative error code. The caller can use IS_ERR to check whether the returned pointer is an error code.
inline long IS_ERR(const void *ptr){return (unsigned long)ptr > (unsigned long)-1000L;}
|
You can use the PTR_ERR function to extract the actual error code.
inline long PTR_ERR(const void *ptr){return (long) ptr;}
|
PTR_ERR can be used only when IS_ERR returns true.