使用 popen 时找不到命令
Command not found when using popen
我在用 C 语言工作,在使用以下参数调用 popen 时遇到问题:
void exampleFunction(void)
{
.
.
.
FILE* in = popen("alias -p", "r");
.
.
.
}
当我以这种方式调用 popen
时,我收到以下消息:
alias: -p not found
我不知道到底出了什么问题,因为当我使用以下参数调用 popen
时:
FILE* in = popen("ls -i", "r");
没有问题,我使用的是相同的语法。
也许有人意识到了问题所在。
alias
命令内置于 shell。
popen
,和system()
一样,调用/bin/sh
来执行指定的命令。您的交互式 shell 可能是 bash,它支持 alias
的 -p
选项。 /bin/sh
,根据您的系统配置,可能不会。
无论如何,即使这有效,也不会给您任何有用的信息。 popen()
调用将调用一个新的 shell,并且(同样,取决于您的配置),它可能不会设置您的别名,因为它不是交互式 shell。
ls -i
命令有效,因为 ls
是一个外部命令,所以无论它是从 bash
或 /bin/sh
调用,还是从交互式或非交互式 shell。 (有时 ls
可以定义为别名或 shell 函数,但此类定义通常不会干扰 -i
选项的使用。)
alias
不是可执行程序,而是一个 shell 内置程序(可将其视为 "function in bash scripting language"),因此您无法使用此名称打开进程。您可以尝试愚弄 bash 并将其通过管道输入。类似于这个未经测试的代码段:
FILE* p = popen("/bin/bash", "r"); // Note: on non-Linux-systems you might need another path or rely on $PATH
fprintf(p, "alias -p\n");
请注意,您也不能直接调用别名。
与 ls
的区别在于 ls
既作为内置程序又作为程序存在。
我在用 C 语言工作,在使用以下参数调用 popen 时遇到问题:
void exampleFunction(void)
{
.
.
.
FILE* in = popen("alias -p", "r");
.
.
.
}
当我以这种方式调用 popen
时,我收到以下消息:
alias: -p not found
我不知道到底出了什么问题,因为当我使用以下参数调用 popen
时:
FILE* in = popen("ls -i", "r");
没有问题,我使用的是相同的语法。
也许有人意识到了问题所在。
alias
命令内置于 shell。
popen
,和system()
一样,调用/bin/sh
来执行指定的命令。您的交互式 shell 可能是 bash,它支持 alias
的 -p
选项。 /bin/sh
,根据您的系统配置,可能不会。
无论如何,即使这有效,也不会给您任何有用的信息。 popen()
调用将调用一个新的 shell,并且(同样,取决于您的配置),它可能不会设置您的别名,因为它不是交互式 shell。
ls -i
命令有效,因为 ls
是一个外部命令,所以无论它是从 bash
或 /bin/sh
调用,还是从交互式或非交互式 shell。 (有时 ls
可以定义为别名或 shell 函数,但此类定义通常不会干扰 -i
选项的使用。)
alias
不是可执行程序,而是一个 shell 内置程序(可将其视为 "function in bash scripting language"),因此您无法使用此名称打开进程。您可以尝试愚弄 bash 并将其通过管道输入。类似于这个未经测试的代码段:
FILE* p = popen("/bin/bash", "r"); // Note: on non-Linux-systems you might need another path or rely on $PATH
fprintf(p, "alias -p\n");
请注意,您也不能直接调用别名。
与 ls
的区别在于 ls
既作为内置程序又作为程序存在。