diff options
author | LAN-TW <lantw44@gmail.com> | 2013-10-30 13:56:32 +0800 |
---|---|---|
committer | LAN-TW <lantw44@gmail.com> | 2013-10-30 13:56:32 +0800 |
commit | 90c80b485fc25bd51edf95ca2cba9e140eb3ec1e (patch) | |
tree | 3a318092b18856de91a1e8b197e88869a2aee7aa | |
parent | 56c2d804f889a6fd8f59c15e4d7f7f75d108ab19 (diff) | |
download | cn2013-90c80b485fc25bd51edf95ca2cba9e140eb3ec1e.tar.gz cn2013-90c80b485fc25bd51edf95ca2cba9e140eb3ec1e.tar.zst cn2013-90c80b485fc25bd51edf95ca2cba9e140eb3ec1e.zip |
HW1: 加入 cd 與 pwd 指令
-rw-r--r-- | hw1/shell.c | 32 | ||||
-rw-r--r-- | hw1/xwrap.c | 3 |
2 files changed, 34 insertions, 1 deletions
diff --git a/hw1/shell.c b/hw1/shell.c index 3a85dc0..febaf6b 100644 --- a/hw1/shell.c +++ b/hw1/shell.c @@ -93,6 +93,25 @@ typedef enum { APPEND_LAST } RasShellCmdMode; +static int ras_shell_builtin_cd (int argc, char* argv[], RasShell* shell) { + if (shell->attr_rshell) { + fprintf (stderr, "%s: you are not permitted to run this command\n", argv[0]); + return 1; + } + char* dest = argv[1]; + if (dest == NULL) { + dest = getenv ("HOME"); + if (dest == NULL) { + dest = "."; + } + } + if (chdir (dest) < 0) { + fprintf (stderr, "cd: %s: %s\n", dest, strerror (errno)); + return 1; + } + return 0; +} + static int ras_shell_builtin_echo (int argc, char* argv[], RasShell* shell) { for (int i = 1; argv[i] != NULL; i++) { if (i > 1) { @@ -139,6 +158,17 @@ static int ras_shell_builtin_printenv (int argc, char* argv[], RasShell* shell) return 0; } +static int ras_shell_builtin_pwd (int argc, char* argv[], RasShell* shell) { + char* cwd = xgetcwd (); + if (cwd == NULL) { + fprintf (stderr, "%s: cannot get working directory: %s\n", argv[0], strerror (errno)); + return 1; + } + puts (cwd); + free (cwd); + return 0; +} + static int ras_shell_builtin_setenv (int argc, char* argv[], RasShell* shell) { if (argc != 3) { fprintf ( @@ -341,9 +371,11 @@ static void ras_shell_cmd_print (RasShellCmd* cmd) { static int ras_shell_cmd_run (RasShellCmd* cmd, RasShell* shell) { const static RasShellBuiltin builtins[] = { + { "cd", ras_shell_builtin_cd }, { "echo", ras_shell_builtin_echo }, { "exit", ras_shell_builtin_exit }, { "printenv", ras_shell_builtin_printenv }, + { "pwd", ras_shell_builtin_pwd }, { "setenv", ras_shell_builtin_setenv }, { "umask", ras_shell_builtin_umask }, { NULL, NULL } diff --git a/hw1/xwrap.c b/hw1/xwrap.c index 4659751..85991ae 100644 --- a/hw1/xwrap.c +++ b/hw1/xwrap.c @@ -4,6 +4,7 @@ #include "xwrap.h" +#include <errno.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> @@ -101,7 +102,7 @@ char* xgetcwd (void) { size = size > 0 ? size : 256; cwd = xmalloc (sizeof (char) * size); - while ((result = getcwd (cwd, size)) == NULL) { + while ((result = getcwd (cwd, size)) == NULL && errno == ERANGE) { size *= 2; cwd = xrealloc (cwd, size); } |