Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define _GNU_SOURCE
- #include <stdio.h>
- #include <sys/types.h>
- #include <sys/wait.h>
- #include <unistd.h>
- #include <string.h>
- #include <stdlib.h>
- void prompt() {
- char hostname[1024];
- hostname[1023] = '\0';
- gethostname(hostname, 1023);
- char pwd[1024];
- getcwd(pwd, sizeof (pwd));
- printf("%s@%s/%s$", getlogin(), hostname, pwd);
- }
- void cd(char *argv[]) {
- if(argv[1] == NULL) {
- const char* home = getenv("HOME");
- printf("%s", home);
- chdir(home);
- } else {
- chdir(argv[1]);
- }
- }
- void help() {
- printf("Helping\n");
- }
- void help1() {
- printf("Helping\n");
- }
- int main() {
- char *line = NULL;
- size_t len;
- ssize_t nread;
- int status = 0;
- while (1) {
- // prompt
- if (status != 0 && WIFEXITED(status))
- printf("(\033[31m%d\033[0m) ", WEXITSTATUS(status));
- prompt();
- // read the line and strip newline
- nread = getline(&line, &len, stdin);
- if (nread == -1)
- break;
- if (line[nread-1] == '\n')
- line[nread-1] = '\0';
- // change spaces into zero bytes
- // and initialize argv
- char *argv[100] = { 0 };
- char *p = line;
- int i = 0;
- while (*p) {
- argv[i] = p;
- ++i;
- while (*p && *p != ' ')
- ++p;
- if (*p == ' ')
- *p = '\0';
- ++p;
- }
- if(strcmp(argv[0], "cd") == 0) {
- cd(argv);
- }
- else if(strcmp(argv[0], "help") == 0) {
- help();
- }
- else if(strcmp(argv[0], "exit") == 0) {
- exit(0);
- }
- else if (memchr(argv[0], '=', sizeof(argv[0]))){
- putenv(argv[0]);
- }
- else {
- if (fork()) {
- // parent
- wait(&status);
- } else {
- //child
- execvp(argv[0], argv);
- printf("command not found: %s\n", argv[0]);
- return 1;
- }
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement