2.9.1 Example: Displaying System Call Errors (errno.d)

The following is an example of the D program, errno.d. In this example, the program displays the value of errno and the file name if an error occurs when using the open() system call to open a file.

#!/usr/sbin/dtrace -qs

/* errno.d -- Display errno and the file name for failed open() calls */

  self->filename = copyinstr(arg0);

/arg0 < 0/
  printf("errno = %-2d   file = %s\n", errno, self->filename);

If an error occurs in the open() system call, the return probe sets the arg0 argument to -1 and the value of the built-in errno variable indicates the nature of the error. A predicate is used to test the value of arg0. Alternatively, you could test whether the value of errno is greater than zero.

When you have saved this script to a file and made the file executable, you can then run it to display information about any failures of the open() system call that occur on the system. After you have started the script, in a separate terminal window, you can run commands that result in an error, such as running the ls command to list a file that does not exist. Or, as in the following example, from another terminal the cat command has been issued on a directory, which results in an error:

# ./errno.d

errno = 2    file = /usr/share/locale/en_US.UTF-8/LC_MESSAGES/libc.mo
errno = 2    file = /usr/share/locale/en_US.utf8/LC_MESSAGES/libc.mo
errno = 2    file = /usr/share/locale/en_US/LC_MESSAGES/libc.mo
errno = 2    file = /usr/share/locale/en.UTF-8/LC_MESSAGES/libc.mo
errno = 2    file = /usr/share/locale/en.utf8/LC_MESSAGES/libc.mo
errno = 2    file = /usr/share/locale/en/LC_MESSAGES/libc.mo