1

我是 C 编程语言的新手,我正在尝试做一个我自己设定的练习。

我想要做的是能够读取用户编写的命令然后执行它。我还没有为此编写任何代码,我真的不确定如何去做。

这基本上是我想要做的:

显示用户提示(让用户输入命令,例如 /bin/ls -al)读取并处理用户输入

我目前正在使用 MINIX 来尝试创建一些东西并更改操作系统。

谢谢

4

3 回答 3

0

这是我到目前为止的代码:

包括

int main(void) {
    char *line = NULL;  
    size_t linecap = 0; 
    ssize_t linelen;    

    while ((linelen = getline(&line, &linecap, stdin)) > 0){
        printf("%s\n", line);
    }

}

这显然会继续执行并打印出一行,直到我按下 CTRL-D。我现在将使用什么样的代码来执行用户输入的命令?

于 2014-11-04T18:43:13.770 回答
0

我给你一个方向:

使用gets读取一行:http ://www.cplusplus.com/reference/cstdio/gets/

你可以用 printf 显示

并使用系统执行调用:http ://www.tutorialspoint.com/c_standard_library/c_function_system.htm

阅读有关此功能的一些信息,让您熟悉它们。

于 2014-11-04T15:43:19.083 回答
0

Shell 在新进程中执行命令。这就是它的一般工作方式:

while(1) {
    // print shell prompt
    printf("%s", "@> ");
    // read user command - you can use scanf, fgets or whatever you want
    fgets(buffer, 80, stdin);
    // create a new process - the command is executed in the new child process
    pid = fork();
    if (pid == 0) {
        // child process
        // parse buffer and execute the command using execve
        execv(...);
    } else if (pid > 0) {
        // parent process
        // wait until child has finished
    } else {
        // error
    }
}
于 2014-11-04T15:43:58.553 回答