Advertisement
Guest User

kira123

a guest
Jan 23rd, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. #define _GNU_SOURCE
  2. #include <stdio.h>
  3. #include <sys/types.h>
  4. #include <sys/wait.h>
  5. #include <unistd.h>
  6. #include <string.h>
  7. #include <stdlib.h>
  8.  
  9.  
  10. void prompt() {
  11. char hostname[1024];
  12. hostname[1023] = '\0';
  13. gethostname(hostname, 1023);
  14. char pwd[1024];
  15.  
  16. getcwd(pwd, sizeof (pwd));
  17. printf("%s@%s/%s$", getlogin(), hostname, pwd);
  18. }
  19. void cd(char *argv[]) {
  20. if(argv[1] == NULL) {
  21. const char* home = getenv("HOME");
  22. printf("%s", home);
  23. chdir(home);
  24. } else {
  25. chdir(argv[1]);
  26. }
  27. }
  28. void help() {
  29. printf("Helping\n");
  30. }
  31.  
  32. void help1() {
  33. printf("Helping\n");
  34. }
  35.  
  36. int main() {
  37. char *line = NULL;
  38. size_t len;
  39. ssize_t nread;
  40. int status = 0;
  41. while (1) {
  42. // prompt
  43. if (status != 0 && WIFEXITED(status))
  44. printf("(\033[31m%d\033[0m) ", WEXITSTATUS(status));
  45. prompt();
  46.  
  47. // read the line and strip newline
  48. nread = getline(&line, &len, stdin);
  49. if (nread == -1)
  50. break;
  51. if (line[nread-1] == '\n')
  52. line[nread-1] = '\0';
  53.  
  54. // change spaces into zero bytes
  55. // and initialize argv
  56. char *argv[100] = { 0 };
  57. char *p = line;
  58. int i = 0;
  59. while (*p) {
  60. argv[i] = p;
  61. ++i;
  62. while (*p && *p != ' ')
  63. ++p;
  64. if (*p == ' ')
  65. *p = '\0';
  66. ++p;
  67. }
  68. if(strcmp(argv[0], "cd") == 0) {
  69. cd(argv);
  70. }
  71. else if(strcmp(argv[0], "help") == 0) {
  72. help();
  73. }
  74. else if(strcmp(argv[0], "exit") == 0) {
  75. exit(0);
  76. }
  77. else if (memchr(argv[0], '=', sizeof(argv[0]))){
  78. putenv(argv[0]);
  79. }
  80. else {
  81. if (fork()) {
  82. // parent
  83. wait(&status);
  84. } else {
  85. //child
  86. execvp(argv[0], argv);
  87. printf("command not found: %s\n", argv[0]);
  88. return 1;
  89. }
  90. }
  91. }
  92. return 0;
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement