当前位置 博文首页 > lyndon_li的博客:35 行代码实现一个简单的 shell
shell.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#define MAXLINE 4096 /* max line length */
int main(int argc, char *argv[])
{
char buf[MAXLINE];
pid_t pid;
int status;
printf("%% "); /* print prompt (printf requires %% to print %) */
while (fgets(buf, MAXLINE, stdin) != NULL) {
if (buf[strlen(buf) - 1] == '\n')
buf[strlen(buf) - 1] = '\0'; /* replace newline with NULL */
if ((pid = fork()) < 0) {
perror("fork error");
} else if (pid == 0) { /* child */
execlp(buf, buf, (char *)0); /* The exec() functions return only if an error has occurred. */
fprintf(stderr, "couldn't execute: %s: %s\n", buf, strerror(errno));
exit(127);
} else { /* parent */
if ((pid = waitpid(pid, &status, 0)) < 0)
perror("waitpid error");
printf("%% ");
}
}
exit(0);
}
编译
$ gcc shell.c -o shell
运行
$ ./shell
% date
2021年 06月 06日 星期日 01:56:28 CST
% who
liyongjun :0 2021-05-23 09:43 (:0)
liyongjun tty3 2021-05-23 20:24
liyongjun tty4 2021-05-25 00:23
liyongjun pts/2 2021-05-25 00:50 (127.0.0.1)
% ls
shell shell.c
% ^D
$