Question

In: Computer Science

Proc,Forks,Exec Examine the code given and do changes as mentioned in the steps below: #include "HALmod.h"...

Proc,Forks,Exec

Examine the code given and do changes as mentioned in the steps below:

#include "HALmod.h"

int GetCommand (string tokens [])
{
string commandLine;
bool commandEntered;
int tokenCount;

do
{
cout << "HALshell> ";
while (1)
{
getline (cin, commandLine);
commandEntered = CheckForCommand ();
if (commandEntered)
{
break;
}
}
} while (commandLine.length () == 0);

tokenCount = TokenizeCommandLine (tokens, commandLine);

return tokenCount;
}

int TokenizeCommandLine (string tokens [], string commandLine)
{
char *token [MAX_COMMAND_LINE_ARGUMENTS];
char *workCommandLine = new char [commandLine.length () + 1];
int i;
int tokenCount;

for (i = 0; i < MAX_COMMAND_LINE_ARGUMENTS; i ++)
{
tokens [i] = "";
}
strcpy (workCommandLine, commandLine.c_str ());
i = 0;
if ((token [i] = strtok (workCommandLine, " ")) != NULL)
{
i ++;
while ((token [i] = strtok (NULL, " ")) != NULL)
{
i ++;
}
}
tokenCount = i;

for (i = 0; i < tokenCount; i ++)
{
tokens [i] = token [i];
}

delete [] workCommandLine;

return tokenCount;
}


//Do not touch the below function
bool CheckForCommand ()
{
if (cullProcess)
{
cullProcess = 0;
cin.clear ();
cout << "\b\b \b\b";
return false;
}

return true;
}


int ProcessCommand (string tokens [], int tokenCount)
{
if (tokens [0] == "shutdown" || tokens [0] == "restart" || tokens [0] == "lo")
{
if (tokenCount > 1)
{
cout << "HALshell: " << tokens [0] << " does not require any arguments" << endl;
return 1;
}
cout << endl;
cout << "HALshell: terminating ..." << endl;

return 0;
  
}
else
return 1;
}
char ** ConvertToC (string tokens [], int tokenCount)
{
char ** words;
words = (char **) malloc (sizeof (char*) * tokenCount);

for (int i=0; i<tokenCount; i++)
{
words[i]=strdup(tokens[i].c_str());
}
return words;
}



Step 1- Modify the "ConvertToC" function ( last function) as mentioned:

1. allocate an extra "word" for NULL (Hint: tokenCount+1)
2. store the value of NULL into the extra "word"

Step 2- Modify the "ProcessCommand" function ( second last function) as mentioned:

You will be emulating a shell. First, the shell checks for specific commands ("shutdown", "lo", etc). If it does not recognize those commands then, a fork occurs and the child will execute the command as typed.

The algorithm to implement is as follows (Hint: add code inside the else):

1. fork to create a child and parent
2. the child will do the following:
Call the ConverToC function and capture the return into a char** variable
Call execvp sending it two arguments: the first element (or word) of the char** variable, and the entire array
Print an error message
exit
3. the parent will do the following:
wait for the child
return 1
4. don't forget to handle the error case of the fork


//Dont try to run the program, just do the following steps.

Solutions

Expert Solution

Please find the modified functions along with the full program mentioned in the question. Please provide your feedback.

Thanks and Happy learning!

#include "HALmod.h"

int GetCommand(string tokens[])
{
    string commandLine;
    bool commandEntered;
    int tokenCount;

    do
    {
        cout << "HALshell> ";
        while (1)
        {
            getline(cin, commandLine);
            commandEntered = CheckForCommand();
            if (commandEntered)
            {
                break;
            }
        }
    } while (commandLine.length() == 0);

    tokenCount = TokenizeCommandLine(tokens, commandLine);

    return tokenCount;
}

int TokenizeCommandLine(string tokens[], string commandLine)
{
    char *token[MAX_COMMAND_LINE_ARGUMENTS];
    char *workCommandLine = new char[commandLine.length() + 1];
    int i;
    int tokenCount;

    for (i = 0; i < MAX_COMMAND_LINE_ARGUMENTS; i++)
    {
        tokens[i] = "";
    }
    strcpy(workCommandLine, commandLine.c_str());
    i = 0;
    if ((token[i] = strtok(workCommandLine, " ")) != NULL)
    {
        i++;
        while ((token[i] = strtok(NULL, " ")) != NULL)
        {
            i++;
        }
    }
    tokenCount = i;

    for (i = 0; i < tokenCount; i++)
    {
        tokens[i] = token[i];
    }

    delete[] workCommandLine;

    return tokenCount;
}


//Do not touch the below function
bool CheckForCommand()
{
    if (cullProcess)
    {
        cullProcess = 0;
        cin.clear();
        cout << "\b\b \b\b";
        return false;
    }

    return true;
}



int ProcessCommand(string tokens[], int tokenCount)
{
    if (tokens[0] == "shutdown" || tokens[0] == "restart" || tokens[0] == "lo")
    {
        if (tokenCount > 1)
        {
            cout << "HALshell: " << tokens[0] << " does not require any arguments" << endl;
            return 1;
        }
        cout << endl;
        cout << "HALshell: terminating ..." << endl;

        return 0;

    }
    else
    {
        //1. fork to create a child and parent
        pid_t pid = fork();

        //Handle error case for fork()
        if (pid < 0)
        {
            //pid <0 means some error happened while doing fork
            cout << "ERROR: Fork failed to create new process." << endl;
        }
        else if (pid == 0)
        {
            //This means it is the child process
            //1. Call the ConverToC function and capture the return into a char** variable
            char ** words = ConvertToC(tokens, tokenCount);
            //2. Call execvp sending it two arguments : the first element(or word) of the char** variable, and the entire array
            execvp(words[0], tokens);
            //3. Print an error message
            cout << "ERROR: Could not recognise the given command" << endl;
            //4. exit
            exit(0);
        }
        else
        {
            //case where the pid > 0. This means it is parent process
            //1. wait for the child. Wait for the child PID
            int waitReturnStatus;
            pid_t ret = waitpid(pid, &waitReturnStatus, 0);
            if (ret == -1)
            {
                cout << "ERROR: waitpid call failed" << endl;
            }
            //2. return 1
            return 1;

        }

    }
}

char ** ConvertToC(string tokens[], int tokenCount)
{
    char ** words;
    //To store an extra word(NULL), allocate a new space by adding
    //one(1) to the tokenCount during malloc
    words = (char **)malloc(sizeof(char*) * (tokenCount + 1));

    int i = 0;
    for (i = 0; i<tokenCount; i++)
    {
        words[i] = strdup(tokens[i].c_str());
    }
    //Once the loop exits the value of i will be pointing to the
    //last element which was allocated to store the NULL in the 
    //malloc statement above. So just store the NULL value there.
    words[i] = NULL;
    return words;
}

Related Solutions

Question from Operating Systems Proc,Forks,Exec Examine the code given and do changes as mentioned in the...
Question from Operating Systems Proc,Forks,Exec Examine the code given and do changes as mentioned in the steps below: #include "HALmod.h" int GetCommand (string tokens []) { string commandLine; bool commandEntered; int tokenCount; do { cout << "HALshell> "; while (1) { getline (cin, commandLine); commandEntered = CheckForCommand (); if (commandEntered) { break; } } } while (commandLine.length () == 0); tokenCount = TokenizeCommandLine (tokens, commandLine); return tokenCount; } int TokenizeCommandLine (string tokens [], string commandLine) { char *token [MAX_COMMAND_LINE_ARGUMENTS]; char...
I need to make changes to code following the steps below. The code that needs to...
I need to make changes to code following the steps below. The code that needs to be modified is below the steps. Thank you. 1. Refactor Base Weapon class: a.            Remove the Weapon abstract class and create a new Interface class named WeaponInterface. b.            Add a public method fireWeapon() that returns void and takes no arguments. c.             Add a public method fireWeapon() that returns void and takes a power argument as an integer type. d.            Add a public method activate()...
The code below is giving an arithmetic overflow. Correct the below given the below code, so...
The code below is giving an arithmetic overflow. Correct the below given the below code, so that the value of s0 is printed before calling the function fun1, inside the function Fun1 and after returning from Fun1 in main. Upload the corrected .asm or .s file in the drop box. .text main: addi $s0,$zero,2 jal Disp jal Fun1 jal Disp j Exit Fun1: addi $sp,$sp,-4 sw $s0,0($sp) addi $s0,$s0,15 jal Disp lw $s0,0($sp) addi $sp,$sp,4 jr $ra Disp: li $v0,1...
C programming assignment. instructions are given below and please edit this code only. also include screenshot...
C programming assignment. instructions are given below and please edit this code only. also include screenshot of the output //In this assignment, we write code to convert decimal integers into hexadecimal numbers //We pratice using arrays in this assignment #include <stdio.h> #include <stdlib.h> #include <assert.h> //convert the decimal integer d to hexadecimal, the result is stored in hex[] void dec_hex(int d, char hex[]) {    char digits[] ={'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',   ...
Develop and pseudocode for the code below: #include <algorithm> #include <iostream> #include <time.h> #include "CSVparser.hpp" using...
Develop and pseudocode for the code below: #include <algorithm> #include <iostream> #include <time.h> #include "CSVparser.hpp" using namespace std; //============================================================================ // Global definitions visible to all methods and classes //============================================================================ // forward declarations double strToDouble(string str, char ch); // define a structure to hold bid information struct Bid { string bidId; // unique identifier string title; string fund; double amount; Bid() { amount = 0.0; } }; //============================================================================ // Static methods used for testing //============================================================================ /** * Display the bid information...
1) What steps can you take to ensure that code changes made to your dependencies will...
1) What steps can you take to ensure that code changes made to your dependencies will not impact your code? 2) Describe the process of mocking and give some examples of scenarios where it might be used. How does this help us?
Given the below Java code snippet, assuming the code is correct, and the names are meaningful,...
Given the below Java code snippet, assuming the code is correct, and the names are meaningful, select the best answer for the below questions: public static void main(String[] args) { int numStations = 10; int enter = 0; int exit = 0; Train train = new Train(numStations); for (int station = 0; station < numStations; station++) {      enter = enter + train.enterPassengers(station);      exit = exit + train.exitPassengers(station); } System.out.println("Number of passengers entered the train: " + enter); System.out.println("Number...
Modify the object provided in the code below to include a variety of overloaded operators in...
Modify the object provided in the code below to include a variety of overloaded operators in C++. Your object should have the following member variables: 1. float *arr a. A dynamic float array that constitutes the data in your myArray object. 2. int size a. The size of the array that the myArray object holds Modify the provided code to include a variety of overloaded operators Operators to overload: 1. bool operator!=(myArray& obj2) a. Tests to see if the calling...
fix the code with constant expression error exrpession below in visual studio #include <iostream> #include <cstdlib>...
fix the code with constant expression error exrpession below in visual studio #include <iostream> #include <cstdlib> #include <ctime> void insertion_sort(int array[], int size, int start); void heap_sort(int B[], int n); void build_max_heap(int B[], int n); void max_heapify(int B[], int i, int n); void quick_sort(int B[], int p, int r); int partition(int B[], int p, int r); int main() {    int m = 10, Nf = 20000, Ns = 1000, delta = 1000, A[m][Nf];    for (int i = 0;...
how would i change the for loops to while loops in the code below #include<stdio.h> #include<stdlib.h>...
how would i change the for loops to while loops in the code below #include<stdio.h> #include<stdlib.h> int main() { int seed; // Taking seed value as input from the user printf("Enter a seed value (0 to quit): \n"); scanf("%d", &seed); // Running the loop until user enters 0 to quit // count array will count frequency of 0 , 1 , 2 ,3 int count[4]; for (int i = 0; i < 4; i++) count[i] = 0; while (seed !=...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT