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

• Using the Scanner class to obtain input from the user. • Using printf to output...
• Using the Scanner class to obtain input from the user. • Using printf to output information to the user. • Using arithmetic operators to perform calculations. • Using if statements to make decisions based on the truth or falsity of a condition. • Using relational operators to compare variable values. Project 1: Write an application that asks the user to enter two integers, obtains them from the user and prints their sum, product, difference and quotient (division). Sample Output:...
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....
Solve following tasks using MIPS Task Write a program that gets a number from user and...
Solve following tasks using MIPS Task Write a program that gets a number from user and displays “Even”, or “Odd. (If-else) Write a program that input a number from user displays each digit separately. For example if input is 3986, output is  6, 8, 9 ,3. (Loop) Write a program that converts a decimal number to binary. (Loop) Hint for Task 1 and Task 3.     Use, div $tdivident,$tdivider and mfhi $tdestination instructions. For example, Div $t1,$t2 will divide $t1...
Exercise 4 – Lists and input Using a function Write a program that prompts the user...
Exercise 4 – Lists and input Using a function Write a program that prompts the user to input a sequence of words. The program then displays a list of unique words (words that only occurred once, i.e. no repeated).
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.
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,...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT