Search code examples
cforkparent-childexecvp

Attempting to call execvp to run programname supplied through stdin, but call fails each time


Good evening

I have found a few similar questions, but nothing that suffices based on this specific question.

I am forking a child process, and attempting to call execvp to run a simple program which outputs 3 chars to stdout. The program name to be run comes from user input.

For some reason every call to execvp fails for simpleO:

I compile file simpleO.c into simpleO, and then compile and run fork.c. I type simpleO into the prompt when requested to attempt to run, but each time I get the error. Here is the code.

The error message printed by perror is "No such file or directory"

--

fork.c

#include <stdio.h>
#include <unistd.h>/*fork, exec*/
#include <errno.h>/*errno*/
#include <string.h> /*strerror*/
#include <stdlib.h>/*EXIT_FAILURE*/

#define BUFFERSIZE 100

int main(int argc, char *argv[]){
int i = 0;
pid_t pid;
int status;
char buffer[BUFFERSIZE];

fgets(buffer, BUFFERSIZE, stdin);

argv[0] = strtok(buffer, " ");
while (buffer[i] != '\0') {/*analyze each char*/
    if (buffer[i] == ' ')/*based on how many spaces there are*/
        argv[i] = strtok(NULL, " ");/*tokenize, populate argv*/
    i++;
}  

if((pid = fork()) == -1){
    fprintf(stderr, "fork error: %s\n", strerror(errno));
    return EXIT_FAILURE;}
else if (pid==0) {
    int e = execvp(argv[0],argv);
    if (e==-1) {
        perror("Exec failed");
        printf("Process %s\n",argv[0]);
        perror("Process did not run");
        exit(1);
    }
}
else{
    wait(&status);}
return 0;
}

--

simpleO.c

#include <stdio.h>
int main(int argc, char **argv){
    printf("%c",'c');
    printf("%c",'2');
    printf("%c",'1');
return 0;
}

Addl ref: perror prints "No such file or directory"


Solution

  • Okay, look: a key lesson in programming is that when an error message tells you something, you should believe it. So, your program is saying "no such file or directory", and it means the file you're trying to run doesn't exist at whatever path you're trying to use.

    You now know that it's not at the default path, so the next thing to try is to use the absolute path of the executable. Now, given the rest of this, I'd suggest you write a very simple C program that does nothing whatsoever besides trying to fork/exec your child program. No argv vector or anything, just fork and then execvp in the child with the executable path an absolute parth.