I would like to get argv from an LD_PRELOAD library, for instance, let us assume we call
LD_PRELOAD=/path/to/my/fopen ./program input
Inside my custom fopen I would like to get "input", hence the argv[1] of my program (also the argv[2] and so on). Is it possible? How?
Read entire /proc/self/cmdline
file. Command line arguments are separated with \0
.
See man proc
for full details.
Linux example without C standard library or error handling:
#include <unistd.h>
#include <fcntl.h>
#include <linux/limits.h>
int main() {
ssize_t i, n;
char cmdline[ARG_MAX];
int cmdline_fd = open("/proc/self/cmdline", O_RDONLY);
n = read(cmdline_fd, cmdline, sizeof cmdline);
for(i = 0; i < n; ++i)
if(!cmdline[i])
cmdline[i] = ' ';
cmdline[n - 1] = '\n';
write(STDOUT_FILENO, cmdline, n);
return 0;
}
Python version for reference:
cmdline = open('/proc/self/cmdline', 'r').read().replace('\0', ' ').strip()
print(cmdline)