如何使用C函数执行Shell内置命令?

我想通过像execv()这样的C语言函数执行Linux命令“pwd”。

问题是没有一个名为“pwd”的可执行文件,我无法执行“echo $ PWD”,因为echo也是一个没有可执行文件的内置命令。

你应该执行sh -c echo $PWD ; 通常sh -c将执行shell命令。

(事实上​​, system(foo)被定义为execl("sh", "sh", "-c", foo, NULL) ,因此适用于shell内置函数。)

如果您只想要PWD的值,请使用getenv

如果你只想在你的c程序中执行shell命令,你可以使用,

  #include  int system(const char *command); 

在你的情况下,

 system("pwd"); 

问题是没有一个名为“pwd”的可执行文件,我无法执行“echo $ PWD”,因为echo也是一个没有可执行文件的内置命令。

这是什么意思? 你应该能够在/ bin /中找到提到的包

 sudo find / -executable -name pwd sudo find / -executable -name echo 

您可以使用excecl命令

 int execl(const char *path, const char *arg, ...); 

如此处所示

 #include  #include  #include  int main (void) { return execl ("/bin/pwd", "pwd", NULL); } 

第二个参数将是进程表中显示的进程名称。

或者,您可以使用getcwd()函数来获取当前工作目录:

 #include  #include  #include  #define MAX 255 int main (void) { char wd[MAX]; wd[MAX-1] = '\0'; if(getcwd(wd, MAX-1) == NULL) { printf ("Can not get current working directory\n"); } else { printf("%s\n", wd); } return 0; }