実験のために、$PATH
を出力するバイナリを作成しました 、およびwhich
を呼び出します 次のように:
#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;
}
を介して空の環境で実行した場合
env -i ./printpath
次の印刷物が表示されます:
got no path
/usr/bin/which
私の質問は次のとおりです。正しいwhich
$PATH
がない場合でも、バイナリが呼び出されます ?
承認された回答:
system
を使用しました 関数なので、別のシェルを使用してコマンドwhich
を実行します 。 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.
which which
を変更した場合 echo $PATH
へのコマンド :
$ env -i ./a.out
got no path
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
execve
を使用するようにコードを変更した場合 system
の代わりに 、期待どおりの出力が得られます:
#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;
}
コンパイルして実行します:
$ gcc test.c && env -i ./a.out
got no path