I am new to C programming language on Unix and trying to build a shell-like C program. However the program gives error if I try to change the function according to my own choices. For example as it seems /bin/ls -l is working but pwd is not. It may be simple but I couldn't understand the problem.
if (fork() == 0)
{
char* argv[3];
argv[0] = "/bin/ls";
argv[1] = "-l";
argv[2] = NULL;
if(execv(argv[0], argv)==-1)
printf("Error in calling exec!!");
printf("I will not be printed!\n");
}
This function is working. I can clearly see the results on shell. However if I want to change like this, it prints error.
if(fork() == 0){
char * argv[2];
argv[0] = "pwd";
argv[1] = NULL;
if(execv(argv[0], argv) == -1)
printf("Error in calling exec!");
}
The execv
function doesn't search the path for the command to run, so it's not able to find pwd
. It can find ls
because you specified the full path to the executable. Use execvp
instead, which does a path search.
Also, use perror
to print error messages for library/system function. It will tell you why the function failed.
if(execvp(argv[0], argv) == -1)
perror("Error in calling exec!");