-2

我现在正在学习 C,并负责在 Minix 虚拟机中创建一个 shell,我正在使用 Minix 中已经可用的库函数来做到这一点,例如 ls、cd 等...

我遇到了一个问题,在 fork 子进程后,我导致核心转储,而不是执行我的命令

#include<stdio.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>

    /*Initialise variables*/
    int pid;
    char *envp[] = { NULL };
    char userInput[256];

void isParent(){
    int stat;
    waitpid(-1, &stat, 0);
}

int main(int argc, char *argv[]) {

    /*Infinite loop to cause shell to be "permenant"*/
    while(1){
        /*"*" to lead every line*/
        printf("%s","*");
        /*Get user input*/
        scanf("%s", userInput); 
        /*Leave an exit clause, to not be permenantly stuck in loop*/
        if(strcmp(userInput, "exit") == 0){
            exit(1);
        }
        /*create my child process*/
        pid = fork(); 

        /*if process is parent, wait*/
        if (pid != 0){
        isParent(); 
        }
        /*Perform function typed by the user*/
        execve(userInput, &argv[1], envp);          
    }
}

这是到目前为止我正在使用的代码,当将 /bin/ls 作为我的 shell 的参数传递时,我可以让它在一个用户输入中打印 ls,两次,但是它在执行该动作时退出 shell,这它不应该。我希望能够使用其他功能,让它们打印一次,然后返回等待用户输入。

当不传递任何参数时,shell 将只接受“退出”,不接受其他命令。如果我从我的主要方法、execve 或两者中删除参数子句 (argv[]),它们会抛出您所期望的错误。

我已经阅读了有关我使用过的所有功能的文档,并专门选择了它们,所以我很高兴不必更改它们,除非我正在做的事情实际上无法使用它们。

仍在学习 C,所以我会欣赏更小的技术术语或更容易理解的短语。我不确定我的问题之前是否曾提出过问题,但我已经用大约 20 种不同的方式搜索了我的问题,并且我的问题的大多数版本都是为 c++、c# 编写的,或者与我的不相似问题,据我了解。

我还要待几个小时,所以如果我错过了任何信息,请随时发表评论并要求澄清、信息或其他任何信息。

4

1 回答 1

0

改变:

    /*if process is parent, wait*/
    if (pid != 0){
    isParent(); 
    }
    /*Perform function typed by the user*/
    execve(userInput, &argv[1], envp);

至:

    /*if process is parent, wait*/
    if (pid != 0){
    isParent(); 
    }
    else
    {
    /*Perform function typed by the user*/
    execve(userInput, &argv[1], envp);
    _exit(0); /* just in case */
    }
于 2015-11-05T22:46:46.673 回答