Created
March 4, 2015 16:51
-
-
Save lovasoa/b96c67fb706c5ccf569e to your computer and use it in GitHub Desktop.
My first shell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <unistd.h> | |
#include <stdlib.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <sys/wait.h> | |
#define MAXS (255) | |
int main(void) { | |
char command[MAXS]; | |
char * args[MAXS]; | |
char space[] = " \n"; | |
while (1) { | |
printf("> "); | |
fgets(command, MAXS, stdin); | |
strtok(command, space); | |
if (strcmp(command, "exit")==0) { | |
exit(0); | |
} | |
args[0] = command; | |
for (int i=1; i<MAXS; i++) { | |
args[i] = strtok(NULL, space); | |
if (args[i] == NULL) break; | |
*(args[i]-1) = '\0'; | |
} | |
if (fork()==0) { | |
int res = execv(command, args); | |
if (res != 0) perror("Unable to execute command"); | |
} | |
else { | |
int status = 0; | |
wait(&status); | |
if (status != 0) printf("Non-null return value: %d\n", status); | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment