In most cases, you could use putenv(3) (perhaps with snprintf(3) or asprintf(3) ...) before execlp(3). for example:
char buf[64];
memset (buf, 0, sizeof(buf));
snprintf (buf, sizeof(buf), "LD_PRELOAD=%s", yourlibso);
putenv(buf);
and after that your execlp
....
However, both putenv
and snprintf
could fail (or have weird behavior, if yourlibso
happens to contain a long string).
You might test before that yourlibso
is good enough with access(2) or stat(2).
Handling every failure is difficult.
See syscalls(2) and errno(3).
Things are much simpler when yourlibso
is known at compile-time. See a draft C standard such as n2573, or a draft C++ standard such as n3337.
Any ideas how I can achieve this in C or C++ on Linux?
remember that C and C++ are different programming languages.