Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 77 lines (66 sloc) 2.057 kb
266689eb »
2011-03-11 initial commit
1 /*
0fb58ab3 »
2011-03-11 EDUCATIONAL PURPOSES => EDUCATIONAL PURPOSES ONLY
2 * DISCLAIMER: THIS CODE IS FOR EDUCATIONAL PURPOSES ONLY. USE AT YOUR OWN RISKS.
266689eb »
2011-03-11 initial commit
3 *
4 * This code shows the basic workings of a shell.
5 *
6 * Append "/path/to/dashell" to /etc/shells, to make it a valid shell:
7 * sudo echo "/path/to/dashell" >> /etc/shells
8 *
9 * Change your "username"'s shell. "username" should have execute permission for the shell:
10 * chsh --shell /path/to/dashell username
11 *
12 */
13
14 #include <unistd.h>
15 #include <string.h>
16 #include <stddef.h>
17 #include <stdlib.h>
18 #include <stdio.h>
19 #include <ctype.h>
20 #include <sys/signal.h>
21
22 #define STDIN 0
23 #define STDOUT 1
68b197cd »
2011-03-30 Edited dashell.c via GitHub
24 #define STDERR 2
266689eb »
2011-03-11 initial commit
25
26 #define BUFFER_SIZE 1024
27
28 void parse_arguments(char buffer[], int *args_count, char *args[]) {
29 char *delimiters = " \r\n";
30 char *token;
31 *args_count = 0;
32 // "abc def ghi" => {"abc", "def", "ghi"}
33 while(token = strsep(&buffer, delimiters)) {
34 args[*args_count] = token;
35 (*args_count)++;
36 }
37 }
38
39 int main(int argc, const char* argv[]) {
40 // The weird characters are used to format the text's appearance.
41 // See http://en.wikipedia.org/wiki/ANSI_escape_code
42 char prompt[] = "\033[1mdashell\033[2m>\033[0m ";
43 char exec_error[] = "Cannot execute program %s.\n";
44 char buffer[BUFFER_SIZE + 1];
45
46 int args_count;
47 char *args[BUFFER_SIZE];
48
49 int n;
50 while(1) {
51 write(STDOUT, prompt, strlen(prompt) + 1);
52 n = read(STDIN, buffer, BUFFER_SIZE); // Read from STDIN (keyboard input)
53 buffer[n] = '\0'; // Null character to indicate string end
54
55 // "abc def ghi" => {"abc", "def", "ghi"}
56 parse_arguments(buffer, &args_count, args);
57
58 // No arguments
59 if(args_count == 0 || strcmp(args[0], "") == 0) continue;
60
61 // Argument = exit
62 if(strcmp(args[0], "exit") == 0) exit(0);
63
64 pid_t child_pid = fork(); // Duplicate process
65 if(child_pid == 0) {
66 // Child
67 if(execvp(args[0], args) < 0) { // Replace executable code by command passed
68 fprintf(stderr, exec_error, args[0]);
69 }
70 }
71 else {
72 // Parent
73 // Wait for child to finish
74 wait();
75 }
76 }
77 }
Something went wrong with that request. Please try again.