8.3.System Call Error Handling

\(8.3.\)System Call Error Handling

1
2
3
4
if ((pid = fork()) < 0) {
fprintf(stderr, "fork error: %s\n", strerror(errno));
exit(0);
}

  We can simplify this code somewhat by defining the following error-reporting function:

1
2
3
4
5
void unix_error(char *msg) /* Unix-style error */
{
fprintf(stderr, "%s: %s\n", msg, strerror(errno));
exit(0);
}

  We can simplify our code even further by using error-handling wrappers. For a given base function foo, we define a wrapper function Foo with identical arguments but with the first letter of the name capitalized. The wrapper calls the base function, checks for errors, and terminates if there are any problems:

1
2
3
4
5
6
7
8
pid_t Fork(void)
{
pid_t pid;

if ((pid = fork()) < 0)
unix_error("Fork error");
return pid;
}