Question

Write a C program that implements a simple shell. The shell takes a user command as...

Write a C program that implements a simple shell. The shell takes a user command as input and execute the command.

When a shell is started, it should take user command, execute it and display the output.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

#include <stdio.h>
#include<string.h>
#include<stdlib.h>

int main()
{
char buff[100];
char *p;
char *args[10];
int count=0,pid,i;
  
printf("Enter command example =>ls -l \n: ");
  
fgets(buff,sizeof(buff),stdin);
//eliminate /n in buff
buff[strlen(buff)-1]='\0';
printf("Output of user command %s \n",buff);
//alocate memory for 10 array of strings
for(i = 0; i < 10; i++)
{
args[i] = (char*)malloc(20*sizeof(char));
}
//printf("%s\n",buff);
//now make a argument list and add to string array
p=strtok(buff," ");
//printf("%s\n",p);
strcpy(args[count++],p);
while(p!=NULL)
{
  
p = strtok(NULL," ");
if(p == NULL)
break;
//printf("in While %s\n",p);
strcpy(args[count++],p);
}
//after building list of commands , execute command using execvp , for that create child process
/*pid = fork();
if(pid == 0) //child process
{
execvp(args[0],args);
}
else //parent process
{
//wait for chidl to finish
wait(0);
printf("Finished executing user command %s \n",buff);
}*/
//print args
args[count]=NULL;
execvp(args[0],args);
return 0;
}

---------------------------------

//output1
Enter command example =>ls -l   
: ls
Output of user command ls   
a.out main.c   

//output2
Enter command example =>ls -l   
: ls -l   
Output of user command ls -l
total 16
-rwxrwxrwx 1 root root 8928 Oct 15 07:11 a.out
-rwxrwxrwx 1 root root 1615 Oct 15 07:11 main.c

Add a comment
Know the answer?
Add Answer to:
Write a C program that implements a simple shell. The shell takes a user command as...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT