A scopo di sperimentazione ho creato un binario che stampa il $PATH
e chiama which
come segue:
#include <stdlib.h>
#include <stdio.h>
int main() {
char *path = getenv("PATH");
if (path)
printf("got a path: %s\n", path);
else
printf("got no path\n");
system("which which");
return 0;
}
quando lo eseguo in un ambiente vuoto tramite
env -i ./printpath
Ottengo la seguente stampa:
got no path
/usr/bin/which
La mia domanda è:perché il which
è corretto binario chiamato, anche se non c'è $PATH
?
Risposta accettata:
Hai utilizzato system
funzione, quindi utilizzerà un'altra shell per eseguire il comando which which
. Da man system
:
DESCRIPTION
system() executes a command specified in command by calling /bin/sh -c
command, and returns after the command has been completed. During exe‐
cution of the command, SIGCHLD will be blocked, and SIGINT and SIGQUIT
will be ignored.
Se modifichi which which
comando per echo $PATH
:
$ env -i ./a.out
got no path
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
Se modifichi il codice per utilizzare execve
invece di system
, otterrai l'output previsto:
#include <stdlib.h>
#include <stdio.h>
int main() {
char *path = getenv("PATH");
if (path)
printf("got a path: %s\n", path);
else
printf("got no path\n");
execve("echo $PATH");
return 0;
}
Compilalo ed eseguilo:
$ gcc test.c && env -i ./a.out
got no path