Search code examples
c++forkexecvp

Having issues with execvp()


So here is the bit of my code that's giving me problems:

void childProcessHandler(string command){


int argCounter = 0;
for(int i=0; i!=command.size(); i++)
    argCounter+=( command.at(i) == ' ');

char * temp, *token;
char *childArgs[argCounter];

argCounter = 1;

temp = new char [command.size()+1];
strcpy (temp, command.c_str());

token = strtok (temp," ");
childArgs[0] = token;

while (token!=NULL)
{
    token = strtok(NULL," ");
    childArgs[argCounter] = token;
    argCounter++;
}
    
//delete[] temp; //Should remove token as well?

execvp(childArgs[0], childArgs);

cout<<"PROBLEM!"<<endl;
exit(-1);

}

In the main() method my code gets to a point where it forks() (the parent process then waits for the child to exit.) then the child process (process ID == 0 yes?) calls the method childProcessHandler with the user input (command to run + args) as it's argument. Then I tokenize the user input and call execvp on it.

Everything compiles and executes. The line after execvp is never reached because execvp only returns when there is an error yes?

The project is to simulate a unix terminal however when I give it the command "date" nothing gets printed like it should... The child exits and the parent process resumes just fine however nothing is sent back up to the terminal window...

What am I doing wrong?

(Also we were "recommended" to use strtok to tokenize it but if anyone has anything simpler i'm open to opinions.)

THANKS!

EDIT

The above code works, for example, if I type in "date " instead of "date". I think there might be something fishy with the "tokenizer" not putting a null character at the end of the childArgs[] array. I'll play around with that and thanks for the quick responses!

(Ninja edit, also commented out delete[] temp for the time being)


Solution

  • Your childargs vector of pointers point into the bytes allocated in the block of memory "temp". When you free temp, you are removing the memory pointed to by the childargs pointers, possibly corrupting some of the values within your vector.

    Remove the call to delete[] to stop freeing the memory pointed to by the childargs pointers. You will not be leaking memory. Once you call exec_() your entire process image is replaced anyway. The only thing that survives a call to exec_() (for the most part) are your file descriptors.

    As a test, try something a bit more simple: After your call to fork() in the child, just call exec with the path to "date". Make that work before fiddling with the parameter list vector.

    As another test, remove your call to exec, and print out your entire vector of pointers to make sure that your tokenizing is working the way you think it should. Remember that your final entry must be NULL so that you know where the end of the vector is.