i'm having a little trouble getting my program going.
it takes a line of input from cin into a string, parses it on any spaces found, and puts the result into an array of char*'s. however, when it gets to the fork and execl section, the anomalies begin. it seems to loop somewhere, first generating a childID of some number, and the second time generating a 0 for childID. This triggers both the if and else statements in the forking function.
i would think it has to do with the strange way i had the assignment and casting of the string into the char* type. i have no reason to believe that it is perfect, and it was just born as a way to get rid of the compiling errors.
here's the code:
Code:
#include <sys/types.h> // For pid_t
#include <sys/wait.h> // For wait
#include <cstdlib>
#include <cstdio> // For perror and errno
#include <iostream>
#include <unistd.h> // For exec and fork calls
#include <cerrno> // For errno and perror
#include <string>
#include <sstream>
#include <vector>
using namespace std;
string input(vector<string>& history);
void parsing(string command, char* args[]);
void forking(char* args[]);
int main ( int argCount, char *argValues[])
{
int argument;
char *args[255];
int count=0;
vector<string> history;
string command;
string temp;
string temp2;
// call input here:
command=input(history);
// call parsing here:
parsing(command, args);
cout<<"Here are the arguments as detected by the function:" <<endl;
while (args[count]!='\0')
{
cout<<"args[" <<count <<"]=" <<args[count] <<endl;
count++;
}
// call forking here
forking(args);
return EXIT_SUCCESS;
}
string input(vector<string>& history)
{
string command;
cout<<"Enter a command" <<endl;
getline(cin, command);
history.push_back(command);
return command;
}
void parsing(string command, char* args[])
{
string temp2;
string temp;
int count=0;
if (command.find(" ", 0)!=std::string::npos)
{
temp2=command.substr(0, command.find(" ", 0));
args[0]=const_cast <char*>(temp2.c_str());
command.erase(0, command.find(" ", 0));
count++;
}
istringstream parse(command);
while (parse>>temp)
{
args[count]=const_cast <char*>(temp.c_str());
count++;
}
}
void forking(char* args[])
{
pid_t childID;
int status;
childID = fork();
cout<<"childID=" <<childID <<endl;
cout<<"getting to the if statement" <<endl;
if (childID == 0)
{ /* It's the child process */
cout<<"inside the if statement" <<endl;
status = execl (args[0], *args);
cout<<"after execl" <<endl;
if (status == -1)
{
cout << "Error Doing execv! errno = " << errno << endl;
perror("exec");
}
}
else
{
childID = wait(&status);
cout << "Output status of child process " << childID
<< " is " << (status >> 8 & 0xff) << endl;
}
}