我是C编程语言的新手,我正在尝试做一个我自己设置的练习。
我想要做的是能够读入用户编写的命令,然后执行它。我还没有为此编写任何代码,我真的不确定如何做到这一点。
这基本上就是我想要做的:
显示用户提示(供用户输入命令,例如/bin/ls -al)读取并处理用户输入
我目前正在使用MINIX尝试创建一些东西并更改操作系统。
谢谢
发布于 2014-11-04 23:43:19
我会给你一个方向:
使用gets读取一行:http://www.cplusplus.com/reference/cstdio/gets/
可以使用printf显示
并使用system执行此调用:http://www.tutorialspoint.com/c_standard_library/c_function_system.htm
阅读一些关于这个函数的内容,让自己熟悉它们。
发布于 2014-11-04 23:43:59
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-05 02:43:14
这是我到目前为止的代码:
包括
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。现在,我应该使用哪种代码来执行用户键入的命令?
https://stackoverflow.com/questions/26738381
复制相似问题