comparison util.c @ 496:6fc71114d145

Extract function to determine executable directory from load_config so it can be used elsewhere
author Mike Pavone <pavone@retrodev.com>
date Mon, 28 Oct 2013 21:48:46 -0700
parents 39cad98d2789
children 32da1e0d5e55
comparison
equal deleted inserted replaced
495:39cad98d2789 496:6fc71114d145
1 #include <string.h> 1 #include <string.h>
2 #include <stdlib.h> 2 #include <stdlib.h>
3 #include <stdio.h> 3 #include <stdio.h>
4 #include <ctype.h> 4 #include <ctype.h>
5
6 #include <sys/types.h>
7 #include <sys/stat.h>
8 #include <unistd.h>
5 9
6 char * alloc_concat(char * first, char * second) 10 char * alloc_concat(char * first, char * second)
7 { 11 {
8 int flen = strlen(first); 12 int flen = strlen(first);
9 int slen = strlen(second); 13 int slen = strlen(second);
61 return text; 65 return text;
62 } 66 }
63 *text = 0; 67 *text = 0;
64 return text+1; 68 return text+1;
65 } 69 }
70
71 static char * exe_str;
72
73 void set_exe_str(char * str)
74 {
75 exe_str = str;
76 }
77
78 char * readlink_alloc(char * path)
79 {
80 char * linktext = NULL;
81 ssize_t linksize = 512;
82 ssize_t cursize = 0;
83 do {
84 if (linksize > cursize) {
85 cursize = linksize;
86 if (linktext) {
87 free(linktext);
88 }
89 }
90 linktext = malloc(cursize);
91 linksize = readlink(path, linktext, cursize-1);
92 if (linksize == -1) {
93 perror("readlink");
94 free(linktext);
95 linktext = NULL;
96 }
97 } while (linksize > cursize);
98 return linktext;
99 }
100
101 char * get_exe_dir()
102 {
103 static char * exe_dir;
104 if (!exe_dir) {
105 char * linktext = readlink_alloc("/proc/self/exe");
106 if (!linktext) {
107 goto fallback;
108 }
109 char * cur;
110 int linksize = strlen(linktext);
111 for(cur = linktext + linksize - 1; cur != linktext; cur--)
112 {
113 if (*cur == '/') {
114 *cur = 0;
115 break;
116 }
117 }
118 if (cur == linktext) {
119 free(linktext);
120 fallback:
121 if (!exe_str) {
122 fputs("/proc/self/exe is not available and set_exe_str was not called!", stderr);
123 }
124 int pathsize = strlen(exe_str);
125 for(cur = exe_str + pathsize - 1; cur != exe_str; cur--)
126 {
127 if (*cur == '/') {
128 exe_dir = malloc(cur-exe_str+1);
129 memcpy(exe_dir, exe_str, cur-exe_str);
130 exe_dir[cur-exe_str] = 0;
131 break;
132 }
133 }
134 } else {
135 exe_dir = linktext;
136 }
137 }
138 return exe_dir;
139 }