Reputation: 2798
I'm about to write a simple shell in C on Ubuntu.
I thought about using the exevcp()
function.
I'm only able to run the "ls" command, none of the other commands seems to work.
Can someone tell me why is it happening or give me an idea of a better way to build the shell?
My purpose is to build this shell; I don't understand why can't I just take the command line, and put it as it is, into the execvp()
function.
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
int main(int argc,char **argv,char **envp)
{
char* args[] = {"history" , NULL};
execvp(args[0],args);
}
Can you explain to me, please?
Upvotes: 0
Views: 898
Reputation: 753615
The execvp()
system call has two arguments: the name of the program to be executed, and a pointer to a null-terminated list of strings that are the arguments to the command.
For example:
char *args[] = { "ls", "-l", "-t", "-r", ".", 0 };
execvp(args[0], args);
...report error...
You can't simply pass a whole string into execvp()
and expect it to split it up; the invoking code must do that. Note that if string pointed at by the first argument to execvp()
contains a slash, then the $PATH
mechanism is not used to find the command. A plain name (as shown, "ls"
) is searched using $PATH
.
You also have to remember that some commands, such as history
and cd
, are shell built-ins; there is no external executable that you can run to get the same effect You won't be able to run those. Other commands, such as test
(aka [
) are usually implemented as built-ins, but there's also usually a binary in /bin
or /usr/bin
that does (more or less) the same job, which you can therefore invoke.
Upvotes: 1
Reputation: 798566
exec(3)
can only be used to run external programs. history
is a built-in in most shells, and cannot be run this way.
Upvotes: 3