Question

In: Computer Science

Question) The following simple shell program/code using gets() function to obtain input from user. Using the...

Question) The following simple shell program/code using gets() function to obtain input from user. Using the gets() function is potentially dangerous and it allows buffer to overflow.

You need to do following modification in the code;

(a) change the provided code so that you now use fgets() function instead of fget() to obtain input from the user,
(b) make any other necessary changes in the code because of using fgets() function, and
(c) fill in the code for the exectute() function so that the whole program works as expected (a simple shell program).



******************************** C O D E **********************************

/* The program asks for UNIX commands to be typed and inputted to a string*/
/* The string is then "parsed" by locating blanks etc. */
/* Each command and corresponding arguments are put in a args array */
/* execvp is called to execute these commands in child process */

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>

void parse(char *buf, char **args);
void execute(char **args);
char *gets(char *s);

int main(int argc, char *argv[])
{
    char buf[1024];
    char *args[64];

    for (;;) {
        /*
         * Prompt for and read a command.
         */
        printf("Command: ");

        if (gets(buf) == NULL) {
            printf("\n");
            exit(0);
        }

        /*
         * Split the string into arguments.
         */
        parse(buf, args);

        /*
         * Execute the command.
         */
        execute(args);
    }
}

/*
 * parse--split the command in buf into
 *         individual arguments.
 */
void parse(char *buf, char **args)
{
    while (*buf != '\0') {
        /*
         * Strip whitespace.  Use nulls, so
         * that the previous argument is terminated
         * automatically.
         */
        while ((*buf == ' ') || (*buf == '\t'))
            *buf++ = '\0';

        /*
         * Save the argument.
         */
        *args++ = buf;

        /*
         * Skip over the argument.
         */
        while ((*buf != '\0') && (*buf != ' ') && (*buf != '\t'))
            buf++;
    }

    *args = NULL;
}

/*
 * execute--spawn a child process and execute
 *           the program.
 */
void execute(char **args)
{
//fill in your code here

}

Solutions

Expert Solution

The solution to the above question is given below with screenshot of output.

=====================================================

I kept the logic simple and i have tested all outputs.

I Have added comments in program so that it can be easily

understood.

If there is anything else do let me know in comments.

=====================================================

============ CODE TO COPY ===============================

main.c

/* The program asks for UNIX commands to be typed and inputted to a string*/
/* The string is then "parsed" by locating blanks etc. */
/* Each command and corresponding arguments are put in a args array */
/* execvp is called to execute these commands in child process */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>

void parse(char *buf, char **args);
void execute(char **args);
char *gets(char *s);

int main(int argc, char *argv[])
{
    char buf[1024];
    char *args[64];

    for (;;) {
        /*
         * Prompt for and read a command.
         */
        printf("Command: ");

        // Updated gets() to fgets()
        if (fgets(buf,1024,stdin) == NULL) {
            printf("\n");
            exit(0);
        }

        /*
         * Split the string into arguments.
         */
        parse(buf, args);

        /*
         * Execute the command.
         */
        execute(args);
    }
}

/*
 * parse--split the command in buf into
 *         individual arguments.
 */
void parse(char *buf, char **args)
{
    while (*buf != '\0') {
        /*
         * Strip whitespace.  Use nulls, so
         * that the previous argument is terminated
         * automatically.
         */
        while ((*buf == ' ') || (*buf == '\t'))
            *buf++ = '\0';

        /*
        *
        */
        int length = strlen(buf);
        if( buf[length-1] == '\n' )
          buf[length-1] = 0;

        /*
         * Save the argument.
         */
        *args++ = buf;

        /*
         * Skip over the argument.
         */
        while ((*buf != '\0') && (*buf != ' ') && (*buf != '\t'))
            buf++;
    }

    *args = NULL;
}

/*
 * execute--spawn a child process and execute
 *           the program.
 */
void execute(char **args)
{
  int pid = fork(); 
  
  if(pid < 0) {
    printf("Error Creating child process");
    return;
  }
  else if(pid == 0) {
    // Child process
    execvp(args[0], args);
  }
  else {
    // Parent process
    wait(0);
  }
}

=====================================================

Output :


Related Solutions

C++ code please: Write a program that first gets a list of integers from input. The...
C++ code please: Write a program that first gets a list of integers from input. The input begins with an integer indicating the number of integers that follow. Then, get the last value from the input, which indicates how much to multiply the array by. Finally, print out the entire array with each element multiplied by the last input. Assume that the list will always contain less than 20 integers. Ex: If the input is 4 4 8 -4 12...
Using C Write a program that will serve as a simple shell. This shell will execute...
Using C Write a program that will serve as a simple shell. This shell will execute an infinite for loop. In each iteration of the loop, the user will be presented with a prompt. When the user enters a command, the shell will tokenize the command, create a child process to execute it and wait for the child process to be over. If the user enters an invalid command, the shell should recognize the situation and show a meaningful message....
Code using assembly language Create a program using the Irvine32 procedures were the user can input...
Code using assembly language Create a program using the Irvine32 procedures were the user can input a list of 32-bit unsigned integers an “x” number of times, then display these integers to the console in reverse order. Hint: Use loops and PUSH & POP instructions. Extra Challenge: Inform the user with a message what to do; also, tell them what they are seeing.
Question: Conversion Program * This program will ask the user to input meters * After input,...
Question: Conversion Program * This program will ask the user to input meters * After input, a menu will be displayed: * 1. Convert to kilometers * 2. Convert to inches * 3. Convert to feet * 4. Quit * * The user will select the conversion and the converted answer will be displayed. * The program should redisplay the menu for another selection. * Quit program when user selects 4. Hi, my instructor requirement fix the bug in the...
Write a simple MIPS program that asks the user to input a string and then a...
Write a simple MIPS program that asks the user to input a string and then a character. The program should then count how many times that character appears in the string and print out that value. Please use comments.
(CODE IN PYTHON) Program Input: Your program will display a welcome message to the user and...
(CODE IN PYTHON) Program Input: Your program will display a welcome message to the user and a menu of options for the user to choose from. Welcome to the Email Analyzer program. Please choose from the following options: Upload text data Find by Receiver Download statistics Exit the program Program Options Option 1: Upload Text Data If the user chooses this option, the program will Prompt the user for the file that contains the data. Read in the records in...
Write a simple JAVA program to understand natural language. The user will enter the input following...
Write a simple JAVA program to understand natural language. The user will enter the input following the format: Name came to City, Country in Year. For example: Chris came to Bangkok, Thailand in 2009. The user will follow the exactly the same formats for the inputs. Your program should be able to analyze the key words (Name, City, Country and Year) from the inputs and reorganize the outputs following format: Name stay in City for X year(s). City is in...
Write a program that first gets a list of integers from input. The input begins with...
Write a program that first gets a list of integers from input. The input begins with an integer indicating the number of integers that follow. Assume that the list will always contain fewer than 20 integers. That list is followed by two more integers representing lower and upper bounds of a range. Your program should output all integers from the list that are within that range (inclusive of the bounds). For coding simplicity, follow each output integer by a space,...
create a program using IDLE where you will gather input from the user using a loop....
create a program using IDLE where you will gather input from the user using a loop. The user needs to provide you with a list of test scores for two categories (two different classrooms). Test scores must be integer values between 0 and 10. You need to process each score so that you can output the following: Number of test scores entered for classroom A. Number of test scores entered for classroom B. Average of test scores entered for classroom...
create a program using IDLE where you will gather input from the user using a loop....
create a program using IDLE where you will gather input from the user using a loop. The user needs to provide you with a list of test scores for two categories (two different classrooms). Test scores must be integer values between 0 and 10. You need to process each score so that you can output the following: Number of test scores entered for classroom A. Number of test scores entered for classroom B. Average of test scores entered for classroom...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT