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
execvfunction doesn't search the path for the command to run, so it's not able to findpwd. It can findlsbecause you specified the full path to the executable. Useexecvpinstead, which does a path search.Also, use
perrorto print error messages for library/system function. It will tell you why the function failed.