// code snippets for the first part of the gosh shell project: // - printing the prompt in interactive mode // - getting lines of input // - properly tokenizing each line // - terminating cleanly when end-of-file is received. this is // ctrl-d in interactive mode // - replacing keyboard input with file input when in batch mode // include files I've used so far #include #include #include #include #include #include #include #include #include #include char *line; size_t n; char *token; int len; char *nxt; line = NULL; n = 0; // get line of input from stdin. getline() allocates the buffer // to store the line len = getline(&line, &n, stdin); // getline() return -1 on error. If errno is 0, the "error" is that // end-of-file has been reached if (len == -1 && errno == 0) // strsep() manipulates it first argument. So that we can properly free // the buffer later, copy its address to nxt and have strsep() manipulate // nxt nxt = line; // tokenize the line of input. the delimiters are space, tab, and newline // characters token = strsep(&nxt, " \t\n"); // if delimiter characters are repeated, zero-length tokens will be //returned. these tokens should be ignored if (strlen(token) > 0) // when finished with the line of input, free the buffer free(line); // if we're processing a batch file, (try to) open the file and replace // stding with the file's file descriptor int fd = open(argv[1], O_RDONLY); dup2(fd, STDIN_FILENO); // the file will now be accessed through stdin. close the duplicate // descriptor close(fd);