Question

In: Computer Science

I am writing a shell program in C++, to run this program I would run it...

I am writing a shell program in C++, to run this program I would run it in terminal like the following: ./a.out "command1" "command2"

using the execv function how to execute command 1 and 2 if they are stored in argv[1] and argv[2] of the main function?

Solutions

Expert Solution

Look at my code and in case of indentation issues check the screenshots.

---------main.cpp---------------

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

using namespace std;

void parseCommand(char *line, char **cmd) //splits the line into words and stores in cmd array
{
   while (*line != '\0') /* if not the end of line ....... */
   {   
       while (*line == ' ' || *line == '\t' || *line == '\n')
           *line++ = '\0'; /* replace white spaces with \0 */
       *cmd++ = line; /* save the argument position */
       while (*line != '\0' && *line != ' ' && *line != '\t' && *line != '\n')
           line++; //skip till end of next argument
   }
   *cmd = NULL; /* mark the end of argument list */
}

void executeCommand(char **argv) //calls execvp and executes the command
{
   int r = execvp(*argv, argv);   //ececutes the command
   if(r < 0)
   {  
       printf("*** ERROR: exec failed\n");
       exit(1);
   }
}

int main(int argc, char *argv[])
{
   if(argc !=3)
   {
       cout << "Usage ./a.out command1 command2 " << endl;
       return -1;
   }
   char *cmd1[10]; //to store command words
   char *cmd2[10]; //to store command words
   int status;

   parseCommand(argv[1], cmd1);           //parse the argv[1] command and store the words in cmd1 array
   parseCommand(argv[2], cmd2);           //parse the argv[2] command and store the words in cmd2 array

   int pid1 = fork(); //forks to create a child
   if(pid1 == 0) //CHILD1
   {
       cout << "\nChild Process, pid = " << getpid() << " executes " << argv[1] << endl;
       executeCommand(cmd1); //calls execvp and executes the command
   }
   else //PARENT
   {
       cout << "\nParent Process, pid = " << getpid() << endl;
       waitpid (pid1, &status, 0); //waits for the child process to terminate

       int pid2 = fork(); //forks to create another child
       if(pid2 == 0) //CHILD2
       {
           cout << "\nChild Process, pid = " << getpid() << " executes " << argv[2] << endl;
           executeCommand(cmd2); //calls execvp and executes the command
       }
       else //PARENT
       {
           cout << "\nParent Process, pid = " << getpid() << endl;
           waitpid (pid2, &status, 0); //waits for the child process to terminate
       }
   }

   return 0;
}

----------Screenshots--------------

----------Output--------------

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

Do comment if you need any clarification.
Please let me know if you are facing any issues.
Please Rate the answer if it helped.

Thankyou


Related Solutions

C Programming Run Length Encoder (Compression). I am writing a program that takes an image (from...
C Programming Run Length Encoder (Compression). I am writing a program that takes an image (from a text file) and looks for patterns of 2 or more duplicate values. The program should replace these values with the following pattern:  2 such characters followed by an Integer ( which represents number of occurrences of each character), followed by an asterisk. For example say the input of the non-compressed image was: ,,,,)H 7. i.e. it consists of four commas, one closed bracket, the...
This is in Python I am getting an error when I run this program, also I...
This is in Python I am getting an error when I run this program, also I cannot get any output. Please help! #Input Section def main(): name=input("Please enter the customer's name:") age=int(input("Enter age of the customer: ")) number_of_traffic_violations=int(input("Enter the number of traffic violations: ")) if age <=15 and age >= 105: print('Invalid Entry') if number_of_traffic_violations <0: print('Invalid Entry') #Poccessing Section def Insurance(): if age < 25 and number_of_tickets >= 4 and riskCode == 1: insurancePrice = 480 elif age >=...
I am writing a program that will work with two other files to add or subtract...
I am writing a program that will work with two other files to add or subtract fractions for as many fractions that user inputs. I need to overload the + and - and << and >> opperators for the assignment. The two files posted cannot be modified. Can someone correct the Fraction.ccp and Frction.h file that I am working on? I'm really close. // // useFraction.cpp // // DO NOT MODIFY THIS FILE // #include "Fraction.h" #include<iostream> using namespace std;...
Hello, I am writing the initial algorithm and refined algorithm for a program. I just need...
Hello, I am writing the initial algorithm and refined algorithm for a program. I just need to make sure I did it correctly. I'm not sure if my formula is correct. I appreciate any help, thank you! TASK: Write a program that will calculate the final balance in an investment account. The user will supply the initial deposit, the annual interest rate, and the number of years invested. Solution Description: Write a program that calculates the final balance in an...
I am writing a matlab program where I created a figure that has a few different...
I am writing a matlab program where I created a figure that has a few different elements to it and now I need to move that figure into a specific excel file into a specific set of boxes in the excel file. With numbers and text I have always used the xlswrite function for this in order to put data into specific boxes. How do I do the same with this figure? The figure I have is called like this:...
What am i doing wrong. I want for the program to run through then when it...
What am i doing wrong. I want for the program to run through then when it gets to "do you want to play again?enter yes or no" if they choose yes I want it to run again if they choose no then end. def play(): print("Welcome to the Game of Life!") print("A. Banker") print("B. Carpenter") print("C. Farmer") user_input = input("What is your occupation? ").upper() if user_input == "A": money = 100 elif user_input == "B": money = 70 elif user_input...
I am trying to create a makefile for the following program in Unix. The C++ program...
I am trying to create a makefile for the following program in Unix. The C++ program I am trying to run is presented here. I was wondering if you could help me create a makefile for the following C++ file in Unix and show screenshots of the process? I am doing this all in blue on putty and not in Ubuntu, so i don't have the luxury of viewing the files on my computer, or I don't know how to...
I am having a trouble with a python program. I am to create a program that...
I am having a trouble with a python program. I am to create a program that calculates the estimated hours and mintutes. Here is my code. #!/usr/bin/env python3 #Arrival Date/Time Estimator # # from datetime import datetime import locale mph = 0 miles = 0 def get_departure_time():     while True:         date_str = input("Estimated time of departure (HH:MM AM/PM): ")         try:             depart_time = datetime.strptime(date_str, "%H:%M %p")         except ValueError:             print("Invalid date format. Try again.")             continue        ...
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....
I am writing a paper on the dealiest epidemics in recorded history. I am looking for...
I am writing a paper on the dealiest epidemics in recorded history. I am looking for information on the polio virus, thypoid fever, and the black palgue. I need help identifying when these diseases started, what started them, the virus or mutation that caused them, how they spread and the preventative measures to stop them.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT