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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19209141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:38:49  来源:igfitidea点击:

How do I execute a Shell built-in command with a C function?

cshellcommandexecpwd

提问by user2851770

I would like to execute the Linux command "pwd" through a C language function like execv().

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

The issue is that there isn't an executable file called "pwd" and I'm unable to execute "echo $PWD", since echo is also a built-in command with no executable to be found.

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

采纳答案by Kerrek SB

You should execute sh -c echo $PWD; generally sh -cwill execute shell commands.

你应该执行sh -c echo $PWD; 一般sh -c会执行shell命令。

(In fact, system(foo)is defined as execl("sh", "sh", "-c", foo, NULL)and thus works for shell built-ins.)

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

If you just want the value of PWD, use getenv, though.

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

回答by smRaj

If you just want to execute the shell command in your c program, you could use,

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

   #include <stdlib.h>

   int system(const char *command);

In your case,

在你的情况下,

system("pwd");


The issue is that there isn't an executable file called "pwd" and I'm unable to execute "echo $PWD", since echo is also a built-in command with no executable to be found.

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

What do you mean by this? You should be able to find the mentioned packages in /bin/

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

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

回答by PhillipD

You can use the excecl command

您可以使用 execl 命令

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

Like shown here

就像这里显示的一样

#include <stdio.h>
#include <unistd.h>
#include <dirent.h>

int main (void) {

   return execl ("/bin/pwd", "pwd", NULL);

}

The second argument will be the name of the process as it will appear in the process table.

第二个参数将是进程的名称,因为它将出现在进程表中。

Alternatively, you can use the getcwd() function to get the current working directory:

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

#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#define MAX 255

int main (void) {
char wd[MAX];
wd[MAX-1] = '##代码##';

if(getcwd(wd, MAX-1) == NULL) {
  printf ("Can not get current working directory\n");
}
else {
  printf("%s\n", wd);
}
  return 0;
}