source: liacs/os/assignment1/simple-shell.c@ 226

Last change on this file since 226 was 2, checked in by Rick van der Zwet, 15 years ago

Initial import of data of old repository ('data') worth keeping (e.g. tracking
means of URL access statistics)

File size: 3.0 KB
RevLine 
[2]1/*
2 * Rick van der Zwet
3 * 0433373
4 * OS Assigment 1 - Part B
5 * Licence: BSD
6 * $Id: simple-shell.c 487 2008-02-20 12:51:08Z rick $
7 */
8
9#include <stdio.h>
10#include <unistd.h>
11#include <stdlib.h>
12#include <string.h>
13
14int main (int argc, char * argv[]) {
15
16 char **ap; /* Argument list pointer */
17 char *argv_c[256]; /* argument input list */
18 char *bp; /* Buffer pointer */
19 char *commandsep = " \t"; /* Command seperation characters */
20 char *pathsep = ":"; /* Path seperation character */
21 char *pathv[256]; /* path list */
22 char fullpath[1024] = ""; /* fullpath to binary */
23 char inbuf[256]; /* input buffer */
24 int argc_c; /* Argument list lengh */
25 int i; /* tmp loop counter */
26 int pathc = 0; /* path list lengh */
27
28 /* Input argument viewer */
29 printf("Number of arguments %i\n", argc);
30 for (i = 0; i < argc; i++) {
31 printf("Command line argument %i: %s\n", i, argv[i]);
32 }
33
34 /* put ENV:PATH into path list */
35 printf("Env PATH=%s\n", getenv("PATH"));
36 bp = getenv("PATH");
37 for (ap = pathv;
38 (*ap = strsep(&bp, pathsep)) != NULL;) {
39 pathc++;
40 if (**ap != '\0')
41 if (++ap >= &pathv[256])
42 break;
43 }
44
45
46
47 /* Main shell */
48 for (;;) {
49 /* Get input */
50 printf("$ ");
51 fgets(inbuf, 256, stdin);
52 inbuf[strlen(inbuf) - 1] = '\0';
53
54 /* Convert input to arguments */
55 bp = inbuf;
56 argc_c = 0;
57 for (ap = argv_c;
58 (*ap = strsep(&bp, commandsep)) != NULL;) {
59 printf("Argument %i : '%s'\n",argc_c, argv_c[argc_c]);
60 argc_c++;
61 if (**ap != '\0')
62 if (++ap >= &argv_c[256])
63 break;
64 }
65
66 /* Catch special cases */
67 if ( argv_c[0] == '\0' ) {
68 printf("No input...\n");
69 continue;
70 }
71 if (strcmp(argv_c[0], "exit") == 0) {
72 printf("Goodbye...\n");
73 break;
74 }
75
76 /* Find proper executable in path */
77 for (i = 0; i < pathc; i++) {
78 (void)strcpy(fullpath, pathv[i]);
79 (void)strcat(fullpath, "/");
80 (void)strcat(fullpath, argv_c[0]);
81 printf("Searching at '%s': ", fullpath);
82
83 if (access(fullpath, X_OK) == 0) {
84 printf("OK\n");
85 /* Execute command, using fork */
86 int pid = fork();
87 if (pid > 0) {
88 wait(NULL);
89 break;
90 } else {
91 printf("Executing: %s ", fullpath);
92 for (i = 1; i < argc_c; i++) {
93 printf("%s ",argv_c[i]);
94 }
95 printf("\n");
96 execv(fullpath, argv_c);
97 }
98 } else {
99 printf("FAILED\n");
100 }
101 }
102 }
103 return(0);
104}
Note: See TracBrowser for help on using the repository browser.