2
#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);
    }
}

此代码似乎不适用于 cd 命令。我该如何修复它?我对操作系统的概念相当陌生,任何帮助将不胜感激!:)

4

1 回答 1

12

cd不作为可执行命令存在。(它不能,因为一个进程只能改变它自己的工作目录,而不是它的父进程的工作目录。)你需要cd使用系统调用将自己实现为内置,chdir()类似于你已经实现的方式quit

如果您打算实现它们,您还需要将其他命令实现为内置命令,包括(例如,我并不想彻底):

  • pushdpopd
  • exit, logout,bye
  • fg, bg, jobs, 和&后缀
  • history
  • set,unset, export
于 2013-09-08T16:50:44.900 回答