Design and implement C/C++ program (myshell5.c) to process command (to tokenize
ID: 3850358 • Letter: D
Question
Design and implement C/C++ program (myshell5.c) to process command (to tokenize and parse the command, and print its components correctly). Your C/C++ program should be able to parse each command from user (to process one command after the other in a loop), until the user's command entered is "exit" to terminate the program.
Examples (You may create your own output format or template to show the command(s) being parsed.)
Run your program for each of the following examples, to show it is working correctly.
#3. Two commands with pipe.
For example, ls | wc should be parsed and display
Command: ls
Pipe
Command: wc
Explanation / Answer
The code is given below :
#include <stdio.h>
#include <sys/types.h>
void parse(char *line, char **argv)
{
while (*line != '') { /* if not the end of line ....... */
while (*line == ' ' || *line == ' ' || *line == ' ')
*line++ = ''; /* replace white spaces with 0 */
*argv++ = line; /* save the argument position */
while (*line != '' && *line != ' ' &&
*line != ' ' && *line != ' ')
line++; /* skip the argument until ... */
}
*argv = ''; /* mark the end of argument list */
}
void execute(char **argv)
{
pid_t pid;
int status;
if ((pid = fork()) < 0) { /* fork a child process */
printf("*** ERROR: forking child process failed ");
exit(1);
}
else if (pid == 0) { /* for the child process: */
if (execvp(*argv, argv) < 0) { /* execute the command */
printf("*** ERROR: exec failed ");
exit(1);
}
}
else { /* for the parent: */
while (wait(&status) != pid) /* wait for completion */
;
}
}
void main(void)
{
char line[1024]; /* the input line */
char *argv[64]; /* the command line argument */
while (1) { /* repeat until done .... */
printf("Shell -> "); /* display a prompt */
gets(line); /* read in the command line */
printf(" ");
parse(line, argv); /* parse the line */
if (strcmp(argv[0], "exit") == 0) /* is it an "exit"? */
exit(0); /* exit if it is */
execute(argv); /* otherwise, execute the command */
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.