To implement the cd command, you need the chdir system call.
#include <unistd.h> int chdir( const char *path );
So you can just call something like:
int ret1 = chdir("../foo/bar");
The return value of chdir is 0 when it was possible to change to this directory and -1 if an error occurred. For error you must consolidate the man page.
The current directory can be checked by any program, therefore, if you execute ls without any arguments, then ls checks which directory it is running in, and uses this directory as the only argument. This is an ls function, not an execv call.
For the second part.
#include <unistd.h> int execv( const char *path, char *const argv[] );
execv executes the executable in the given path and with the arguments given in argv . So if you want to execute /bin/ls ../foo /bar , you need something similar to
char *cmd_str = "/bin/ls"; char *argv[] = {cmd_str, "../foo", "/bar", NULL }; if (execv(cmd_str, argv) == -1 ){ }
The error returned by execv is -1. If you want to know why he did not execute the command, check the manual pages.
NULL in char *argv[] = {cmd_str, "../foo", "/bar", NULL }; indicates that there are no other arguments after NULL .
The third part. A Unix-based system typically processes commands using a / in as commands that can be executed directly. This means that you first check for a slash on the given command line.
int ret_value; if (strchr(cmd_str, '/') if (execv(cmd_str, argv) == -1 ){ }
If there is no slash, you need to go through all the directories in path and check if you can execute the command. Thus, this command is ls ../foo /bar and suggests that the path value is ".:/sbin:/bin:/usr/bin" . Then we tried to execute ./ls ../foo /bar , then /usr/bin/ls ../foo /bar and finally /bin/ls ../foo /bar .
Hope this helps.