空の環境で実行ファイルを見つける方法は?

空の環境で実行ファイルを見つける方法は?

実験目的で、次のように$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

ベストアンサー1

functionを使用したので、system別のシェルを使用してコマンドを実行しますwhich 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

おすすめ記事