Guest User

Untitled

a guest
Nov 19th, 2017
584
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.79 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <sys/types.h>
  4. #include <sys/wait.h>
  5. #include <unistd.h>
  6. #include <stdlib.h>
  7.  
  8. #define MAX_ARGS 256
  9.  
  10. int main()
  11. {
  12.         char* input = NULL;
  13.         size_t n = 0;
  14.  
  15.         printf("***MIRKOSHELL***\n");
  16.         printf("type exit to exit\n");
  17.  
  18.         while (1)
  19.         {
  20.                 printf("> ");
  21.  
  22.                 /*czytanie wejscia z kosoli*/
  23.                 ssize_t bytes_read = getline(&input, &n, stdin);
  24.                 if (bytes_read <= 0) {
  25.                         fprintf(stderr, "Invalid input\n");
  26.                         continue;
  27.                 }
  28.                 if (input[bytes_read - 1] == '\n')
  29.                         input[bytes_read - 1] = 0;
  30.  
  31.                 /*tutaj sprawdzamy, czy komenda na wejsciu jest exit, jezeli jest wychodzimy z
  32.                  * petli while, konczac program*/
  33.                 if (strcmp(input, "exit") == 0) {
  34.                         break;
  35.                 }
  36.  
  37.                 char* args[MAX_ARGS + 1] = { strtok(input, " "), 0 };
  38.                 char* ptr;
  39.                 int i = 1;
  40.                 while ((ptr = strtok(NULL, " ")) && i < MAX_ARGS)
  41.                         args[i++] = ptr;
  42.  
  43.                 /*tworzymy fork naszego programu*/
  44.                 int pid = fork();
  45.                 /*sprawdzamy czy fork zostal wykonany pomyslnie*/
  46.                 if (pid == -1) {
  47.                         perror("fork");
  48.                         exit(EXIT_FAILURE);
  49.                 } else if (pid == 0) {
  50.                         execvp(args[0], args);
  51.                         perror("execvp");
  52.                         exit(EXIT_FAILURE);
  53.                 } else {
  54.                         waitpid(pid, NULL, 0);
  55.                 }
  56.  
  57.         }
  58.     exit(EXIT_SUCCESS);
  59.     return 0;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment