0

I want to use the execl function to invoke both commands cd and vi from my c program, but it does not work. This is what I did for rm and ls:

execl("/bin/ls", "ls", NULL);
execl("/bin/rm", "rm", args[1], NULL); //args is the array containing the arguments of the command

It works for ls and rm, but when I try to do the same thing with vi and cd it does not work.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • There was [this](https://stackoverflow.com/questions/46370470/execvp-in-c-not-going-through-ar) question like 10 minutes ago. And for some reason your `cd` and `vi` do not match the code with `ls` and `rm`. – Eugene Sh. Sep 22 '17 at 18:18
  • If you try to exec `cd` it won't work, partly because `cd` is a builtin to the shell, not a standalone program you can exec, and also because, if you change directory in a subprocess, it doesn't affect the parent (which is precisely why it has to be a builtin to the shell). `vi`, on the other hand, should have worked, unless maybe if there were problems getting its hand on the terminal -- since of course it's a highly interactive program. – Steve Summit Sep 22 '17 at 18:21
  • 1
    What is the failure mode when you try to exec `vi`? Can you show us the exact code you used for that? – Steve Summit Sep 22 '17 at 18:48
  • Since you don't show the code that failed, it's hard to know what went wrong. On a Mac, there _is_ a command `/usr/bin/cd`, but it is of very, very limited use — the command changes directory, but doesn't affect the invoking program. (If I run `/usr/bin/cd /some/where/non-existent`, it gives an error message `/usr/bin/cd: line 4: cd: /some/where/non-existent: No such file or directory`. So, it could be used to check whether the target directory exists and is accessible, but that's about it. And yes, it is a shell script.) – Jonathan Leffler Sep 22 '17 at 18:51
  • Note that if you are writing a shell, you will not be using `execl()` very often. You will need to use `execv()`, `execvp()`, `execve()` or `execvpe()` depending on context and what's available. – Jonathan Leffler Sep 22 '17 at 18:53
  • As in the question I linked in the first comment: You *can't* use `exec*` functions one after the other as they just don't return in the good case. – Eugene Sh. Sep 22 '17 at 19:09
  • Better to use `execl("/bin/ls", "ls", (char*)NULL);` for rare platforms that do not make `NULL` same size/encoding as a `char*`. OTOH, such machine may not have `execl()`. – chux - Reinstate Monica Sep 22 '17 at 20:11

0 Answers0