CSCI.4220 Network Programming
Unix Exception Handling

There are about 190 Unix system calls (the number varies somewhat from one system to another). They always take the form of a C function call; i.e. they take arguments which can be either ordinary variables or pointers to ordinary variables and they return a value. The value returned is usually of type int, although a few return a pointer. In general, a positive or zero return value indicates that the call was successful, and a negative return value indicates that the system call failed for some reason. If the system call failed, a global external int variable errno will be set, and your program can look at this value to determine why the system call failed. To access this value, put this line at the top of your program.

extern int errno;

Symbolic names for all values of errno are defined in the header file sys/errno.h. You need to look at the man pages for each system call to determine the meaning of these values.

For example, the socket() system call fails if:

     [EPROTONOSUPPORT]  The protocol type or the specified protocol is not
                        supported within this domain.

     [EMFILE]           The per-process descriptor table is full.

     [ENFILE]           The system file table is full.

     [EACCES]           Permission to create a socket of the specified type
                        and/or protocol is denied.

     [ENOBUFS]          Insufficient buffer space is available.  The socket
                        cannot be created until sufficient resources are
                        freed.
If an exception occurs on a system call, you can use the utility function void perror(const char *string);. This displays on standard error your message (in the argument called string) followed by a short message explaining the error. Here is a short sample program in which an attempt to open a file called myfile.txt fails because the file does not exist.
#include <sys/errno.h>
#include <fcntl.h>
#include <stdio.h>

int main()
{
  int retval;

  retval = open("myfile.txt",O_RDONLY);
  if (retval < 0) {
    perror("Error opening myfile.txt");
    exit(0);
  }
  return 0;
}

This will display the following message on standard error
Error opening myfile.txt: No such file or directory

There is also a function char *strerror(int errno) (make sure to include the header file string.h) which returns a string corresponding to the error number passed in as an argument. You could display this string on standard error with this statement:

fprintf(stderr,"%s\n",strerror(errno));

It is good programming practice to always check the return value of a system call that might fail (some system calls cannot fail), and take appropriate steps in the event of a failure. This will be required for all programming in this course.

Here are links to the man pages for these functions
perror()
strerror()