| 1 |
/*********************************************************************** |
| 2 |
* Code listing from "Advanced Linux Programming," by CodeSourcery LLC * |
| 3 |
* Copyright (C) 2001 by New Riders Publishing * |
| 4 |
* See COPYRIGHT for license information. * |
| 5 |
***********************************************************************/ |
| 6 |
|
| 7 |
#include <errno.h> |
| 8 |
#include <stdio.h> |
| 9 |
#include <stdlib.h> |
| 10 |
#include <string.h> |
| 11 |
#include <unistd.h> |
| 12 |
|
| 13 |
#include "server.h" |
| 14 |
|
| 15 |
const char* program_name; |
| 16 |
|
| 17 |
int verbose; |
| 18 |
|
| 19 |
void* xmalloc (size_t size) |
| 20 |
{ |
| 21 |
void* ptr = malloc (size); |
| 22 |
/* Abort if the allocation failed. */ |
| 23 |
if (ptr == NULL) |
| 24 |
abort (); |
| 25 |
else |
| 26 |
return ptr; |
| 27 |
} |
| 28 |
|
| 29 |
void* xrealloc (void* ptr, size_t size) |
| 30 |
{ |
| 31 |
ptr = realloc (ptr, size); |
| 32 |
/* Abort if the allocation failed. */ |
| 33 |
if (ptr == NULL) |
| 34 |
abort (); |
| 35 |
else |
| 36 |
return ptr; |
| 37 |
} |
| 38 |
|
| 39 |
char* xstrdup (const char* s) |
| 40 |
{ |
| 41 |
char* copy = strdup (s); |
| 42 |
/* Abort if the allocation failed. */ |
| 43 |
if (copy == NULL) |
| 44 |
abort (); |
| 45 |
else |
| 46 |
return copy; |
| 47 |
} |
| 48 |
|
| 49 |
void system_error (const char* operation) |
| 50 |
{ |
| 51 |
/* Generate an error message for errno. */ |
| 52 |
error (operation, strerror (errno)); |
| 53 |
} |
| 54 |
|
| 55 |
void error (const char* cause, const char* message) |
| 56 |
{ |
| 57 |
/* Print an error message to stderr. */ |
| 58 |
fprintf (stderr, "%s: error: (%s) %s\n", program_name, cause, message); |
| 59 |
/* End the program. */ |
| 60 |
exit (1); |
| 61 |
} |
| 62 |
|
| 63 |
char* get_self_executable_directory () |
| 64 |
{ |
| 65 |
int rval; |
| 66 |
char link_target[1024]; |
| 67 |
char* last_slash; |
| 68 |
size_t result_length; |
| 69 |
char* result; |
| 70 |
|
| 71 |
/* Read the target of the symbolic link /proc/self/exe. */ |
| 72 |
rval = readlink ("/proc/self/exe", link_target, sizeof (link_target) - 1); |
| 73 |
if (rval == -1) |
| 74 |
/* The call to readlink failed, so bail. */ |
| 75 |
abort (); |
| 76 |
else |
| 77 |
/* NUL-terminate the target. */ |
| 78 |
link_target[rval] = '\0'; |
| 79 |
/* We want to trim the name of the executable file, to obtain the |
| 80 |
directory that contains it. Find the rightmost slash. */ |
| 81 |
last_slash = strrchr (link_target, '/'); |
| 82 |
if (last_slash == NULL || last_slash == link_target) |
| 83 |
/* Something stange is going on. */ |
| 84 |
abort (); |
| 85 |
/* Allocate a buffer to hold the resulting path. */ |
| 86 |
result_length = last_slash - link_target; |
| 87 |
result = (char*) xmalloc (result_length + 1); |
| 88 |
/* Copy the result. */ |
| 89 |
strncpy (result, link_target, result_length); |
| 90 |
result[result_length] = '\0'; |
| 91 |
return result; |
| 92 |
} |