I have been trying to implement a shell in Linux as a learning experience...the change directory function and the program itself gives different outputs under different privileges.
1)Execution under normal user authority
[Vivek-lappy]/home/Vivek-lappy/Documents/Zeus/Zeus>ls /
0 dev initrd.img live-build mnt root srv usr
bin etc lib lost+found opt run sys var
boot home lib64 media proc sbin tmp vmlinuz
[Vivek-lappy]/home/Vivek-lappy/Documents/Zeus/Zeus>cd /
PWD=/
[Vivek-lappy]/>ls
Segmentation fault
gdb shows the following errors:
Program received signal SIGSEGV, Segmentation fault.
_IO_vfprintf_internal (s=0x0, format=0x402953 "command:%s\n",
ap=ap@entry=0x7fffffffdd08) at vfprintf.c:1278
1278 vfprintf.c: No such file or directory.
2) Execution under sudo privileges
[root](null)>ls /
0 dev initrd.img live-build mnt root srv usr
bin etc lib lost+found opt run sys var
boot home lib64 media proc sbin tmp vmlinuz
[root](null)>cd /
PWD=/
[root]/>ls
0 dev initrd.img live-build mnt root srv usr
bin etc lib lost+found opt run sys var
boot home lib64 media proc sbin tmp vmlinuz
[root]/>
3) Additional information Code for Change directory function
void add(char * name,char * value){
unsetenv(name);setenv(name,value,1);
}
void dump(char * name){
char * value=getenv(name);
printf("%s=%s\n",name,value);
}
int cd(char * argv[],int argc){
char cwd[1024];
if(argc>2){
printf("\n Too many arguments cd accepts only one argument that is the directory name\n");
return -1;
}
if(argv[1]==NULL){
if(chdir(getenv("HOME"))==0){
add("PWD",getenv("HOME"));
dump("PWD");
return 0;
}
}
if(chdir(argv[1])!=0){
printf("\n No Such Directory\n");
printf("\nUSAGE:> cd Dir_name [Where Directory_Name is the Directory name] \n");
return -1;
}
if (!getcwd (cwd, sizeof(cwd))) {
perror ("getcwd");
exit (EXIT_FAILURE);
}
else{
add("PWD",cwd);
dump("PWD");
}
return 0;
}
Code for execute :
int execute(char * argv[],int argc){
int status;
if(strcmp(argv[0],"cd")==0){
cd(argv,argc);
}
else if(strcmp(argv[0],"list")==0){
list();
}
else if(strcmp(argv[0],"color")==0){
color();
}
else if(strcmp(argv[0],"history")==0){
history();
}
else
{
pid_t pid=fork();
if(pid<0){
fprintf(stderr, "cant fork process%s\n",strerror(errno) );
return 1;
}
else if(pid==0){
if(execvp(argv[0],argv)<0){
fprintf(stderr, "cant run program:%s\n",strerror(errno) );
return 1;
}
}
else
{
while(wait(&status)!=pid)
;
}
}
return 0;
}
Why is the output of the same program different with different privileges?