【问题标题】:Read in users command and execute it读入用户命令并执行
【发布时间】:2014-12-31 12:49:11
【问题描述】:

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

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

这基本上就是我想要做的:

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

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

谢谢

【问题讨论】:

  • 请说明您的问题并发布您已经尝试过的内容。听起来你想为 MINIX 开发一个 shell?所以你需要printfscanfforkexecve
  • 是的,我确实想为 MINIX 开发一个外壳。我想尝试使用以下功能之一:getline、getdelim 和 strtok。我目前还没有尝试过任何事情,因为我不确定如何做到这一点
  • 我只是想要一些关于从哪里开始以及如何开始使用 getline 函数的指南

标签: c input command prompt minix


【解决方案1】:

我会给你一个方向:

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

你可以用 printf 显示

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

阅读一些关于这个函数的信息让你自己熟悉它们。

【讨论】:

  • 谢谢。我想使用 getline 虽然将行读入程序以便它可以执行。
【解决方案2】:

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
    }
}

【讨论】:

  • 我如何将这个过程与 getline 函数一起使用?我可以将 fgets 更改为 getline 吗?
  • 是的,您可以使用getline 而不是fgets
【解决方案3】:

这是我目前的代码:

包括

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。现在我将使用什么样的代码来执行用户输入的命令?

【讨论】:

    猜你喜欢
    • 2013-02-22
    • 2018-11-28
    • 1970-01-01
    • 2012-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多