简体   繁体   中英

cd command not working with execvp

#include <stdio.h>
#include <sys/types.h>
#include <string.h>

int main()
{
    char *ip;
    char *temp[10];
    pid_t pid;

    pid = fork();

    if (pid == 0) {
        int i = 0;

        do {
            gets(ip);

            temp[0] = strtok(ip, " ");
            while (temp[++i] != NULL) {
                temp[i] = strtok(NULL," ");
            }

            pid_t pid2;

            pid2 = fork();
            if (pid2 == 0) {
                execvp(temp[0], temp);
            }
        } while(strcmp(temp[0], "quit"));

        if (!strcmp(temp[0],"quit")) {
            return;
        }
    } else if (pid < 0) {
        fprintf(stderr,"error in creating child");
    } else if (pid > 0) {
        wait(NULL);
    }
}

this code doesnt seem to work with cd command.how do i go about fixing it?i am fairly new to the concepts of OS and any help would be appreciated! :)

cd does not exist as an executable command. (And it cannot, because a process can only change the working directory of itself, not of its parent.) You will need to implement cd yourself as a builtin, using the chdir() system call, similar to the way you've already implemented quit .

Other commands you will need to implement as builtins as well, if you plan to implement them, include (for example, I'm not trying to be thorough):

  • pushd and popd
  • exit , logout , bye , etc
  • fg , bg , jobs , and the & suffix
  • history
  • set , unset, export

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