All the arguments to execle()
except the last two are strings — the penultimate one is a null char *
marking the end of the command line arguments, and the last is a char **
specifying the environment. The first is the pathname of the executable, relative to the current directory if the name does not start with a /
slash. The second argument is the name of the program. Subsequent arguments are the extra arguments for the program (the list is terminated by a (char *)0
argument) and then there's a final argument that is the environment for the program (the trailing e
indicates that the environment is passed). Hence, for example:
extern char **environ; // No header declares this!
execle("teste", "pink elephants", (char *)0, environ);
You could use "teste"
or "/bin/bash"
in place of "pink elephants"
, depending on your tastes. Only two of the three program name options suggested are outright fibs. If you replace the environ
argument with (char **)0
or equivalent, then the program is invoked with no environment variables, which is usually regarded as an abuse of the program that's run (rather like telling it that it's name is "pink elephants
" rather than "teste
" is an abuse of it).
You could use variables too:
const char *progname = "teste";
execle(progname, progname, (char *)0, environ);
Ended up using execlp
and just writing execlp("./teste",NULL,NULL)
; only solution that worked.
It's impressive how many (small) problems there can be in a single simple line of code. Using execlp("./teste", NULL, NULL);
is dubious on at least these counts:
- You've not provided the executed program with its name, which is discourteous at best and leads to unhelpful error reports, etc.
- The first NULL is sufficient if you're not going to provide a name; the second is never processed.
- Using
"./teste"
means that the p
(path search) part of execlp()
is never exercised; you might as well have used execle("./teste", (char *)NULL, environ);
.
- It's not impossible for
NULL
not to translate to (char *)0
in a variable argument list like with execle()
. It's not a very likely problem, but #define NULL 0
is legitimate, and if sizeof(int) == 4
but sizeof(char *) == 8
, then you could have difficulties.
Aside: you'll probably find the execv*()
functions more useful in general than the execl*()
functions. At least, my experience is that the variable length argument list is more often needed by the programs I run than a fixed length list.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…