简体   繁体   中英

How do I use **environ from unistd.h to search for the right path?

Hi I'm trying to use execvp() in conjunction with the **environ variable to find the right path for a command the user puts in.

The problem is I don't really understand how to do this. I know I could just attempt to open the command files to check if they exist but I don't understand how to get the paths I need to search from **environ .

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(void) {
    char *start, *end;
    char ch;
    char* path = getenv("PATH");

    if (!path) {
        fprintf(stderr, "could not get $PATH, exiting\n");
        exit(EXIT_FAILURE);
    }

    start = path;
    do {
        end = strchr(start, ':');
        if (!end) {
            printf("%s\n", start);
        } else {
            ch = *end;
            *end = '\0';
            printf("%s\n", start);
            *end = ch;
        }
        start = end + 1;
    } while (end != NULL);

    return 0;
}

This small program demonstrates how you can get separate paths from env[PATH].

man execvp:

execvp() will duplicate the actions of the shell in searching for an executable file

Thus, you don't have to use the **environ variable to find the right path for a command ; execvp() does it for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM