LiorGolan
LiorGolan

Reputation: 375

Error handling/checking in the kernel realm

What is the equivalent to errno in the kernel realm? More precisely, how do I check what error has happened for example when using a function like kmalloc()?

Upvotes: 2

Views: 5281

Answers (2)

mik1904
mik1904

Reputation: 1365

There isn't a errno in the kernel realm. You can just check the return of a kernel function with an if statement for example for the kmalloc():

struct dog *ptr;

ptr = kmalloc(sizeof(struct dog), GFP_KERNEL);
if (!ptr)
    /* handle error ... */

Where you handle your error you could then decide which would be the errno value in the user space just with:

return -ErrorName;

Linux kernel then interprets this negative value through the library errno.h. You can find the list of Errors to set the errno variable in:

include/asm-generic/errno.h
include/asm-generic/errno-base.h

Upvotes: 2

Ed Schouten
Ed Schouten

Reputation: 530

The Linux kernel uses a couple of different methods for dealing with error conditions. Unlike C userspace programs, functions do not store their error code in a global variable, but return the value directly. You typically see that this is done as follows:

  • Functions that return no value apart from an error code typically return 0 upon success and -ESOMETHING upon failure.
  • Functions that may return a non-negative numerical value (e.g., an index, a file descriptor number or a length in bytes) are similar: 0 or higher indicates success and negative values indicate errors.
  • Functions that return pointers may return a value in a special range to indicate an error. By calling IS_ERR() on the return value, you can check whether an error occurred. With PTR_ERR() you can extract the error code, which is again negated.

Unfortunately, the kmalloc() function uses none of these styles. It returns NULL upon failure without giving you a specific error code.

Upvotes: 6

Related Questions