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...
I am Writing a C-Program to read and write files. but none of my code is...
I am Writing a C-Program to read and write files. but none of my code is working like it should be. Please fix all code and supply output response. Please try to use existing code and code in comments. But if needed change any code that needs to be changed. Thank you in advance //agelink.c //maintains list of agents //uses linked list #include <stdio.h> #include <stdlib.h> #define TRUE 1 void listall(void); void newname(void); void rfile(void); void wfile(void); struct personnel {...
WITHOUT USING POINTERS. This is C programming. I am writing a program which should calculate standard...
WITHOUT USING POINTERS. This is C programming. I am writing a program which should calculate standard deviation of an array of exam scores and then add the standard deviation to each array element. It should print the original array, the standard deviation, and the new rounded adjusted array. I included my question as a comment in the line of code that is giving me an issue. (Removing the a from E-x-a-m as Chegg doesn't allow the word.) #include <stdio.h> #include...
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:...
I am struggling with this assignment. I can't get the program to run when I enter...
I am struggling with this assignment. I can't get the program to run when I enter a number with the $ symbol followed by a number below 10. any help would be greatly appreciated. Create a program named Auction that allows a user to enter an amount bid on an online auction item. Include three overloaded methods that accept an int, double, or string bid. Each method should display the bid and indicate whether it is over the minimum acceptable...
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...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT