2021-10-04 21:35:09 +01:00
|
|
|
// makeCWrapper /path/to/executable \
|
|
|
|
--argv0 my-wrapper \
|
|
|
|
--set-default MESSAGE HELLO \
|
|
|
|
--prefix PATH : /usr/bin/ \
|
|
|
|
--suffix PATH : /usr/local/bin/ \
|
|
|
|
--add-flags "-x -y -z" \
|
|
|
|
--set MESSAGE2 WORLD
|
|
|
|
|
2021-12-01 22:27:26 +00:00
|
|
|
#define _GNU_SOURCE /* See feature_test_macros(7) */
|
2021-10-04 21:35:09 +01:00
|
|
|
#include <unistd.h>
|
|
|
|
#include <stdlib.h>
|
2021-11-09 01:55:26 +00:00
|
|
|
#include <assert.h>
|
2021-12-01 21:49:20 +00:00
|
|
|
#include <stdio.h>
|
|
|
|
|
2021-12-01 21:56:18 +00:00
|
|
|
#define assert_success(e) do { if ((e) < 0) { perror(#e); abort(); } } while (0)
|
2021-10-04 21:35:09 +01:00
|
|
|
|
2021-12-01 22:27:26 +00:00
|
|
|
void set_env_prefix(char *env, char *sep, char *prefix) {
|
2021-10-04 21:35:09 +01:00
|
|
|
char *existing = getenv(env);
|
2021-12-01 22:27:26 +00:00
|
|
|
if (existing) {
|
|
|
|
char *val;
|
|
|
|
assert_success(asprintf(&val, "%s%s%s", prefix, sep, existing));
|
|
|
|
assert_success(setenv(env, val, 1));
|
|
|
|
free(val);
|
|
|
|
} else {
|
|
|
|
assert_success(setenv(env, prefix, 1));
|
|
|
|
}
|
2021-10-04 21:35:09 +01:00
|
|
|
}
|
|
|
|
|
2021-12-01 22:27:26 +00:00
|
|
|
void set_env_suffix(char *env, char *sep, char *suffix) {
|
2021-10-04 21:35:09 +01:00
|
|
|
char *existing = getenv(env);
|
2021-12-01 22:27:26 +00:00
|
|
|
if (existing) {
|
|
|
|
char *val;
|
|
|
|
assert_success(asprintf(&val, "%s%s%s", existing, sep, suffix));
|
|
|
|
assert_success(setenv(env, val, 1));
|
|
|
|
free(val);
|
|
|
|
} else {
|
|
|
|
assert_success(setenv(env, suffix, 1));
|
|
|
|
}
|
2021-10-04 21:35:09 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
int main(int argc, char **argv) {
|
2021-12-01 21:49:20 +00:00
|
|
|
assert_success(setenv("MESSAGE", "HELLO", 0));
|
2021-10-04 21:35:09 +01:00
|
|
|
set_env_prefix("PATH", ":", "/usr/bin/");
|
|
|
|
set_env_suffix("PATH", ":", "/usr/local/bin/");
|
|
|
|
putenv("MESSAGE2=WORLD");
|
|
|
|
|
2021-12-01 22:07:30 +00:00
|
|
|
char **argv_tmp = calloc(4 + argc, sizeof(*argv_tmp));
|
2021-11-09 01:55:26 +00:00
|
|
|
assert(argv_tmp != NULL);
|
2021-10-04 21:35:09 +01:00
|
|
|
argv_tmp[0] = argv[0];
|
|
|
|
argv_tmp[1] = "-x";
|
|
|
|
argv_tmp[2] = "-y";
|
|
|
|
argv_tmp[3] = "-z";
|
|
|
|
for (int i = 1; i < argc; ++i) {
|
|
|
|
argv_tmp[3 + i] = argv[i];
|
|
|
|
}
|
|
|
|
argv_tmp[3 + argc] = NULL;
|
|
|
|
argv = argv_tmp;
|
|
|
|
|
|
|
|
argv[0] = "my-wrapper";
|
|
|
|
return execv("/path/to/executable", argv);
|
|
|
|
}
|