POSIX Error Handling

From LSDevLinux
(Redirected from C Error Handling)
Jump to: navigation, search
#include <string.h>
// Do something that might set errno
// Immediately preserve errno so we don't change it before examining it
int errorNumber = errno;
if (evidence of error) // eg something() may return non-zero or NULL on error
  const int bufLength = 1024;
  char errorMessage[bufLength];
  char *actualErrorMessage = strerror_r(errorNumber, errorMessage, bufLength);
  // actualErrorMessage may or may not be pointing to errorMessage 
  // (so work with actualErrorMessage not errorMessage)

  // Deal with any errors that can be dealt with in a specific way, eg...
  if (ENOENT == errorNumber) {
  else if (EROFS == errorNumber) {
  else // Handler for any errors that don't have special handling
      "libname: Warning: error doing thus-and-such: %s\n",