39

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

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.

user2851770
  • 393
  • 1
  • 3
  • 4

3 Answers3

52

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

   #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.

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

sudo find / -executable -name pwd
sudo find / -executable -name echo
smRaj
  • 1,246
  • 1
  • 9
  • 13
  • I'm still new at this sort of thing. I tried using "which pwd" on the shell and it only returned that "pwd" is a built-in command. Thank you, anyway! – user2851770 Oct 06 '13 at 14:32
  • 1
    Forgive my possible ignorance, but that will just return with the return code rather than stdout, correct? – Jpatrick Aug 30 '19 at 15:02
  • 1
    @Jpatrick You are correct. `system` helps with executing shell commands, and also be able to read the returncode with a couple other system calls. If you want to read the stdout of the program, need to use popen() instead: https://www.gnu.org/software/libc/manual/html_node/Pipe-to-a-Subprocess.html – smRaj Nov 22 '19 at 22:47
27

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

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

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

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
14

You can use the execl() function:

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:

#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;
}
Mahdi Gheidi
  • 55
  • 1
  • 7
PhillipD
  • 1,797
  • 1
  • 13
  • 23