cprocessforkexecvp

execvp() wont load file: "No such file or directory"


I wrote 2 programs. The first one gets 2 strings through argv and prints the program process id and the smallest string (by dictionary order).

int main(int argc,char **argv) {
    int cmp;
    if (argc != 3){
        perror("Wrong arguments");
        exit(EXIT_FAILURE);

    }
    printf("my ID: %d\n",getpid());
    cmp = strcmp(argv[1],argv[2]);
    if (cmp < 0)
        puts(argv[1]);

    else if (cmp > 0)
        puts(argv[2]);

    else puts(argv[1]);

    exit(EXIT_SUCCESS);
}

I have compiled the code via terminal with:

gcc -Wall my_cmp.c -o my_cmp

The second program creates a child process and performs execvp() with my_cmp sending "abc" "de".

void do_sun(char **argv);

int main() {
    pid_t status;
    char *args[] = { "my_cmp", "abc","de", NULL };

    status = fork();

    if (status < 0){
        perror("Cannot fork");
        exit(EXIT_FAILURE);
    }
    if (status == 0){
        char *args[] = { "my_cmp", "abc","de", NULL };
        do_sun(args);
        exit(EXIT_SUCCESS);
    }

    if (status > 0){
        wait(&status);
        if (execvp(args[0],args) != 0 )
            perror("error");
        exit(EXIT_SUCCESS);
    }
    exit(EXIT_SUCCESS);
}

void do_sun(char **args){
    if (execvp(args[0],args) == -1 )
                perror("error");
    exit(EXIT_SUCCESS);
}

When I run the program I am getting this message:

error: No such file or directory
error: No such file or directory

I have tried to switch directory to the my_cmp file with no success.


Solution

  • On some systems it won't search working directory for executable binary files by default.

    You should use ./my_cmp instead of my_cmp to have it work on such systems.