FRI-OS
example/posix/c-error_handling.c

Shows basic error message formatting

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <error.h>
int main(int argc, const char* argv[])
{
const char* badpath = "!#$%^&/";
// this call will fail
execlp(badpath, badpath, NULL);
// perror, when called immediately after
// a failed system call prints a message
// describing the error that has occured
perror("Exec failed");
// another possibility
// this will again fail
// syscalls use a convention that an error
// is indicated by returning -1
// and the global errno variable is set
if(open(badpath, 0) == -1)
{
// if the call failed remember the value of errno
// which may be overwritten by subsequent syscalls
int error = errno;
// allocate a temporary buffer
char buffer[1024] = {'\0'};
// use the (reentrant version of the) strerror function
// to get the error message associated with the error code
const char* msg = strerror_r(error, buffer, 1024);
// use the message
printf("Exec failed with error code %d = '%s'\n", error, msg);
}
// yet another possibility
// again creat returns -1 on failure and sets errno
if(creat(badpath, O_CREAT) < 0)
{
int error = errno;
error_at_line(
0, // <- passing a nonzero here would cause the process to exit
error,
__FILE__,
__LINE__,
"Exec of '%s' failed",
badpath
);
}
return 0;
}