《Linux从练气到飞升》No.21 Linux简单实现一个shell
warning:
这篇文章距离上次修改已过200天,其中的内容可能已经有所变动。
下面是一个简单的Linux shell的示例实现,它可以接受命令并输出结果。这个例子仅支持一些基本命令,并且没有错误处理。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main() {
char command[1024];
while (1) {
printf("my_shell> "); // 提示符
fgets(command, sizeof(command), stdin); // 从标准输入读取一行
command[strcspn(command, "\n")] = 0; // 移除行尾的换行符
if (fork() == 0) { // 子进程中执行命令
execlp(command, command, (char*)NULL);
perror("execlp failed");
exit(EXIT_FAILURE);
}
int status;
wait(&status); // 父进程等待子进程结束
}
return 0;
}
这段代码使用了fork()
来创建一个子进程,然后在子进程中使用execlp()
来执行用户输入的命令。父进程使用wait()
来等待子进程结束。
注意:这个例子没有处理命令不存在或者命令执行出错的情况,也没有处理输入命令行的解析,仅作为一个简单的示例来说明shell的基础原理。在实际应用中,一个完整的shell需要处理许多复杂的情况。
评论已关闭