POSIX Error Handling

From LSDevLinux
Jump to: navigation, search
#include <string.h>
// Do something that might set errno
something();
// 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) {
    create_file_and_try_again();
    ...
  }
  else if (EROFS == errorNumber) {
    prompt_user_for_writable_path();
    ...
  }
  else // Handler for any errors that don't have special handling
  {
    fprintf(stderr,
      "libname: Warning: error doing thus-and-such: %s\n",
      actualErrorMessage);
  }
}