阅读用户命令并执行它

问题描述:

我是C编程语言的新手,我正在尝试做一个我自己设定的练习。阅读用户命令并执行它

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

这基本上是什么,我想要做:

显示用户提示(用于用户输入的命令例如/ bin中/ LS -al) 读取并处理所述用户输入

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

感谢

+0

请指定您的问题并发布您已经尝试过的内容。听起来你想为MINIX开发一个shell?所以你需要printf,scanf,fork和execve。 – 2014-11-04 15:18:34

+0

是的,我确实想为MINIX开发一个shell。我想尝试使用其中一个函数:getline,getdelim和strtok。我目前还没有尝试过任何操作,因为我不确定如何操作 – user3411748 2014-11-04 15:25:17

+0

我只是想从某种指南开始,以及如何从getline函数开始 – user3411748 2014-11-04 15:32:59

我会给你一个方向:

利用获取到读取一行:http://www.cplusplus.com/reference/cstdio/gets/

你可以用printf的显示

和使用系统执行呼叫:http://www.tutorialspoint.com/c_standard_library/c_function_system.htm

读一点关于这个功能让你自己熟悉它们。

+0

谢谢。我想使用getline来读取程序中的行,以便它可以被执行。 – user3411748 2014-11-04 15:52:28

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

我将如何使用getline函数的这个过程?我是否会将fgets改为getline? – user3411748 2014-11-04 15:48:40

+0

是的,你可以使用'getline'而不是'fgets'。 – 2014-11-04 15:52:28

这是我的代码至今:

包括

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