This repository was archived by the owner on Nov 20, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogdir.c
More file actions
92 lines (83 loc) · 2.22 KB
/
Copy pathprogdir.c
File metadata and controls
92 lines (83 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#if defined(_WIN32)
#include <windows.h>
#define _PATH_MAX MAX_PATH
#else
#define _PATH_MAX PATH_MAX
#endif
#if defined (__CYGWIN__)
#include <sys/cygwin.h>
#endif
#if defined(__linux__) || defined(__sun)
#include <unistd.h> /* readlink */
#endif
#if defined(__APPLE__)
#include <sys/param.h>
#include <mach-o/dyld.h>
#endif
#if defined(__FreeBSD__)
#include <sys/types.h>
#include <sys/sysctl.h>
#endif
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
char* getprog() {
int nsize = _PATH_MAX + 1;
char* progdir = malloc(nsize * sizeof(char));
char *lb;
int n = 0;
#if defined(__CYGWIN__)
char win_buff[_PATH_MAX + 1];
GetModuleFileNameA(NULL, win_buff, nsize);
cygwin_conv_path(CCP_WIN_A_TO_POSIX, win_buff, progdir, nsize);
n = strlen(progdir);
#elif defined(_WIN32)
n = GetModuleFileNameA(NULL, progdir, nsize);
#elif defined(__linux__)
n = readlink("/proc/self/exe", progdir, nsize);
if (n > 0) progdir[n] = 0;
#elif defined(__sun)
pid_t pid = getpid();
char linkname[256];
sprintf(linkname, "/proc/%d/path/a.out", pid);
n = readlink(linkname, progdir, nsize);
if (n > 0) progdir[n] = 0;
#elif defined(__FreeBSD__)
int mib[4];
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PATHNAME;
mib[3] = -1;
size_t cb = nsize;
sysctl(mib, 4, progdir, &cb, NULL, 0);
n = cb;
#elif defined(__BSD__)
n = readlink("/proc/curproc/file", progdir, nsize);
if (n > 0) progdir[n] = 0;
#elif defined(__APPLE__)
uint32_t nsize_apple = nsize;
if (_NSGetExecutablePath(progdir, &nsize_apple) == 0)
n = strlen(progdir);
#else
// FALLBACK
// Use 'lsof' ... should work on most UNIX systems (incl. OSX)
// lsof will list open files, this captures the 1st file listed (usually the executable)
int pid;
FILE* fd;
char cmd[80];
pid = getpid();
sprintf(cmd, "lsof -p %d | awk '{if ($5==\"REG\") { print $9 ; exit}}' 2> /dev/null", pid);
fd = popen(cmd, "r");
n = fread(progdir, 1, nsize, fd);
pclose(fd);
// remove newline
if (n > 1) progdir[--n] = '\0';
#endif
if (n == 0 || n == nsize || (lb = strrchr(progdir, (int)LUA_DIRSEP[0])) == NULL)
return NULL;
return (progdir);
}