Many error codes are defined in Linux, such as:-enomem,-EINTR, etc. These error codes are essentially negative integers.
However, in the actual code process, the return value of some functions is pointer type, there are some integer type.
For example, the following function:
struct Kfifo * Kfifo_init ()
{
struct KFIFO *kfifo;
Kfifo = kmalloc (sizeof (struct kfifo), gfp_kernel);
if (!KFIFO)
Return-enomem;
}
The return value required by this function is the struct KFIFO * pointer type. While Return-enomem returns a true integer type, a type conflict occurs during use.
So the kernel is how to solve the above problem. Finally, the error code defined in the kernel can be used regardless of whether the return value of the function is a pointer type or an integer type.
The kernel is implemented through the following function interfaces:
static inline void *err_prt (long error)
{
return (void) *error;
}
err_prt (Long errno) is used to convert an error code to a pointer;
You can change the above Kfifo_init () to:
struct Kfifo * Kfifo_init ()
{
struct KFIFO *kfifo;
Kfifo = kmalloc (sizeof (struct kfifo), gfp_kernel);
if (!KFIFO)
Return Err_ptr (-ENOMEM);
}
Static inline long ptr_err (const void *PTR)
{
return (long) PTR;
}
used to convert the pointer to an error code;
Static inline long is_err (const void *ptr)
{
Return Is_err_value ((unsigned long) PTR);
}
used to determine if PTR is an address corresponding to an error code, or 0 if it returns 1;
For example:
struct KFIFO *ret;
ret = Kfifo_init ();
if (Is_err (ret))
Kfree (buffer);
The Kfifo_init () should be returned Err_ptr (-ENOMEM) in the error, so the RET is (void*)-enomem.
Is_err (ret) is used to determine whether the RET is the error code corresponding to the address, if so, return 1;
Interface Summary
long Ptr_err (const void *ptr);
void *err_ptr (long errno);
Long Is_err (const void *ptr);
The above three interfaces are located in <linux/err.h> ;
Error code handling function in Linux kernel