Hi, I'm trying to create a simple shell program that reads in a command from the keyboard and passes it to execvp to execute. I'm working in a Linux environment. I'm splitting the input line into a command (the first token) and arguments (the remaining tokens). For example, ls -l has ls as command and -l as the sole argument. The problem is that execvp does not recognize the first argument. If I input "ls -l", it executes just "ls" and drops the "-l." If I input "ls -l -a", then it executes "ls -a." If I input "ls," it doesn't execute anything. Any thoughts? Thanks! Here is my code:
Code:
#include <unistd.h>
#include <iostream>
#include </usr/include/errno.h>
#include </usr/include/sys/errno.h>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
// issue prompt
cout << "> ";
// get input from user
string inputStr;
char inputStrArr[128];
char * argArr[128];
char separators[] = " ,\t\n";
char *token, *command;
int numArgs = -1;
int k;
int i;
getline(cin, inputStr);
for(i=0; i<inputStr.length(); i++)
inputStrArr[i] = inputStr[i];
inputStrArr[i] = '\0';
token = strtok(inputStrArr, separators);
command = token;
while( token != NULL )
{
token = strtok( NULL, separators );
argArr[++numArgs] = token;
}
argArr[++numArgs] = '\0';
// fork
int childpid, flag;
if ((childpid = fork()) == 0) // child code
{
cout << "Process ID: child: " << getpid();
flag = execvp(command, argArr);
if (flag < 0)
{
perror("execvp failed");
}
}
else if (childpid > 0) // parent code
{
cout << "Process ID: " << getpid();
}
else // fork unsuccessful
{
cout << "\nError: fork failed\n";
}
return 0;
}