smR*_*Raj 26
如果您只想在c程序中执行shell命令,可以使用,
   #include <stdlib.h>
   int system(const char *command);
在你的情况下,
system("pwd");
问题是没有一个名为"pwd"的可执行文件,我无法执行"echo $ PWD",因为echo也是一个没有可执行文件的内置命令.
你这是什么意思?你应该能够在/ bin /中找到提到的包
sudo find / -executable -name pwd
sudo find / -executable -name echo
Ker*_* SB 13
你应该执行sh -c echo $PWD; 通常sh -c会执行shell命令.
(实际上,它system(foo)被定义为execl("sh", "sh", "-c", foo, NULL),因此适用于shell内置函数.)
如果你只是想要的价值PWD,请使用getenv.
您可以使用excecl命令
int execl(const char *path, const char *arg, ...);
如图所示
#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
int main (void) {
   return execl ("/bin/pwd", "pwd", NULL);
}
第二个参数将是进程表中显示的进程名称.
或者,您可以使用getcwd()函数获取当前工作目录:
#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#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;
}