#include <wait.h>
#include <stdio.h>
#include <zconf.h>
#include <cstdlib>
#include <cstring>
#include <cerrno>
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wmissing-noreturn"
int builtin_command(char **argv);
int parse_line(char *, char **argv);
void eval(char *cmd_line);
int main(int argc, char **argv) {
char cmd_line[8888];
while (1) {
printf(">");
fgets(cmd_line, 8888, stdin);
cmd_line[(strlen(cmd_line))] = '\0';
printf(" len:%d", strlen(cmd_line));
eval(cmd_line);
}
}
int builtin_command(char **argv) {
if (strcmp(argv[0], "quit") == 0)
exit(0);
if (strcmp(argv[0], "&") == 0)
return 1;
return 0;
}
void eval(char *cmd_line) {
printf("eval \n");
char *cmd_buf = cmd_line;
char *argv[1000];
printf("%d", strlen(cmd_buf));;
int bg = parse_line(cmd_buf, argv);
if (argv[0] == NULL) {
return;
}
pid_t pid;
if (builtin_command(argv) == 0) {
if ((pid = fork()) == 0) {
if (execve(argv[0], argv, environ) < 0) {
printf("%s :Command not found .\n", argv[0]);
exit(0);
}
}
printf("bg=%d\n",bg);
if (!bg) {
int status;
if (waitpid(pid, &status, 0) < 0) {
fprintf(stderr, "%s", strerror(errno));
exit(0);
}
} else
printf("%d %s", pid, cmd_line);
}
return;
}
int parse_line(char *cmd_buf, char **argv) {
char *delim;
int argc=0;
int bg;
cmd_buf[strlen(cmd_buf) - 1] = ' ';
while (*cmd_buf && (*cmd_buf == ' '))
cmd_buf++;
while ((delim = strchr(cmd_buf, ' '))) {
argv[argc++] = cmd_buf;
*delim = '\0';
cmd_buf = delim + 1;
while (*cmd_buf && (*cmd_buf == ' '))
cmd_buf++;
}
argv[argc] = NULL;
if (argc == 0)
return 1;
if ((bg = (*argv[argc - 1] == '&')) != 0) {
argv[--argc] = NULL;
}
return bg;
}
利用fork和execve运行程序
最新推荐文章于 2023-05-06 23:16:22 发布
这个博客介绍了一个实现shell命令解析和执行的程序。它使用`fork`和`execve`系统调用来运行接收到的命令。程序读取用户输入,通过`fgets`获取命令行,然后使用`builtin_command`检查是否为内置命令,如果不是,则通过`fork`创建子进程,并用`execve`执行外部命令。如果命令结尾带有`&`,则命令在后台运行。
摘要由CSDN通过智能技术生成