Steinfeld
Steinfeld

Reputation: 689

execvp won't execute a command

I am trying to run a piece of code which will execute a few UNIX commands, these commands are stored in the array lineArray which for instance: lineArray = {"ls -l", "ls", "pwd", NULL};

the problem is the this code will only print out the first command in the array even though I have seen on debug that my function parses the commands and its arguments correctly according to the execvp MAN.

Any kind of help will be appreciated.

int startProcesses(int background) {
int i = 0;
int j = 0;
int pid;
int status;
char *copyProcessName[256];
int len, var=0;

while(lineArray[i] != NULL) {

    while(*(copyProcessName+var) != NULL) {
        copyProcessName[var] = NULL;
    }

    j=0;
    copyProcessName[j] = strtok(lineArray[i], " ");
    while (copyProcessName[j] != NULL){
        j++;
        copyProcessName[j] = strtok(NULL, " ");
    }


    pid = fork();

    if (pid == 0) {
        // Child Process
        execvp(copyProcessName[0], copyProcessName);
        fflush(stdout);
        i++;
        continue;

    } else if (!background) {
        // Parent Process
        waitpid(pid, &status, 0);
        i++;
        if(WEXITSTATUS(status)) {
            printf(CANNOT_RUN_ERROR);
            return 1;
        }
    } else {
        i++;
        continue;
    }
}
return 0;

}

Upvotes: 0

Views: 903

Answers (1)

Mats Petersson
Mats Petersson

Reputation: 129314

This code is clearly not right:

len = strlen(copyProcessName);
for (var = 0; var < len; ++var) {
    copyProcessName[var] = NULL;
}

Given that if that len may be zero, we have no idea what the contents of copyProcessName actually contains.

while(*(lineArray+i) != NULL)

what's wrong with:

while(lineArray[i] != NULL)

It's shorter, and it is an array, so you probably want to use the [] to index it.

You should also check the return value of execvp(..) - if it returns, you will want to print what the return value was, as that'll indicate what you may have done wrong.

In the second iteration of the outer loop, j is not zero when you get to the code below, which will probably cause all manner of problems:

copyProcessName[j] = strtok(lineArray[i], " ");
while (copyProcessName[j] != NULL){
    j++;
    copyProcessName[j] = strtok(NULL, " ");
}

This is not a conclusive list of problems with your code, just what I spotted when reading through it rather quickly.

Upvotes: 3

Related Questions