For example, int fork
returns -1
on error. int pipe
also returns -1
on error. int socket
also returns -1
on error.
I want to know, do all
system calls return -1
on error. I've seen code with error checking, and it's all different. Some of them do return value < 0
, some of them do return value == -1
, some of them do return value < 1
, and so, what can I do to error check any system call?
What must I check? Or does it actually depend on the system call? Can I not always do < 0
?
I want to know, do all system calls return -1 on error.
No. Without providing any actual examples, I quote POSIX 1003.1-2008, 2016 Edition:
Most functions can provide an error number. The means by which each function provides its error numbers is specified in its description.
Some functions provide the error number in a variable accessed through the symbol
errno
[...].Some functions return an error number directly as the function value. These functions return a value of zero to indicate success.
The functions that provide error detail via errno
also signal via their return value that an (unspecified) error occurred. Most such signals take the form of a return value of -1.
You go on to inquire:
I've seen code with error checking, and it's all different. Some of them do
return value < 0
, some of them doreturn value == -1
, some of them doreturn value < 1
, and so, what can I do to error check any system call?
Many functions that signal an error by returning -1 do not document any other negative return values. For such functions, testing whether the return value is exactly -1 and testing whether it is negative serve the same purpose. Testing the return value against 1 is not equivalent, but it may nevertheless be valid for some particular contexts, such as when it is used to detect both function failures and function successes that nevertheless indicate an application-level error, such as bad user input.
As the quoted text indicates, each function documents the mechanism by which it signals errors, and how to get the corresponding error number, if any. You check for errors from a particular function by your choice of any approach consistent with its documentation. POSIX contains two main classes of functions in this regard -- those that signal an error by returning -1 and those that do it by returning any of a variety of nonzero values -- but you'll sometimes need also to deal with other functions. If ever you are uncertain, it is always a good idea to consult the documentation of the functions you are using.