From c081d56e4a46e38fd7789672540fc14b02e6caa7 Mon Sep 17 00:00:00 2001 From: cyp0633 Date: Mon, 23 May 2022 23:43:42 +0800 Subject: [PATCH] Shell Lab: eval template and trace01 --- shlab/tsh.c | 38 +++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/shlab/tsh.c b/shlab/tsh.c index 7c2ea8d..a5344ef 100644 --- a/shlab/tsh.c +++ b/shlab/tsh.c @@ -163,8 +163,44 @@ int main(int argc, char **argv) * background children don't receive SIGINT (SIGTSTP) from the kernel * when we type ctrl-c (ctrl-z) at the keyboard. */ -void eval(char *cmdline) +void eval(char *cmdline) { + char *argv[MAXARGS]; + char buf[MAXLINE]; // command will be parsed and modified? + int bg; // whether it runs in background + pid_t pid; + // preprocess cmd line + strcpy(buf, cmdline); + bg = parseline(buf, argv); // convert the command into argv + if (argv[0] == NULL) // the line is empty, return + { + return; + } + // run external command + if (!builtin_cmd(argv)) + { + if ((pid = fork()) == 0) // this is child + { + if (execve(argv[0], argv, environ) < 0) // execute command failed + { + printf("%s: Command not found\n", argv[0]); + exit(0); // here only child exited + } + } + if (!bg) // run the process in foreground: + // wait for foreground job to terminate + { + int status; + if (waitpid(pid, &status, 0) < 0) // if return -1, then waiting failed + { + unix_error("waitfg: waitpid error"); + } + } + else + { + printf("%d %s", pid, cmdline); + } + } return; }