如何使用 C 函数执行 Shell 内置命令? [英] How do I execute a Shell built-in command with a C function?
问题描述
我想通过像execv()这样的C语言函数来执行Linux命令pwd".
I would like to execute the Linux command "pwd" through a C language function like execv().
问题是没有名为pwd"的可执行文件,我无法执行echo $PWD",因为 echo 也是一个内置命令,找不到可执行文件.
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.
推荐答案
你应该执行 sh -c echo $PWD
;通常 sh -c
会执行 shell 命令.
You should execute sh -c echo $PWD
; generally sh -c
will execute shell commands.
(事实上,system(foo)
被定义为 execl("sh", "sh", "-c", foo, NULL)
并因此起作用用于 shell 内置函数.)
(In fact, system(foo)
is defined as execl("sh", "sh", "-c", foo, NULL)
and thus works for shell built-ins.)
如果您只想要PWD
的值,请使用getenv
.
If you just want the value of PWD
, use getenv
, though.
这篇关于如何使用 C 函数执行 Shell 内置命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!