In: Computer Science
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?
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