実験のために、$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