Guest User

Untitled

a guest
Aug 20th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. UNIX simple shell in C, execve and parameters
  2. [...] Preprocesser directives
  3.  
  4. void read_command()
  5. {
  6. int i; //index to the arrays stored in parameter[]
  7. char *cp; //points to the command[]
  8. const char *hash = " "; //figures out the strings seperated by spaces
  9. memset(command, 0, 100); //Clear the memory for array
  10. parameter[0] = "/bn/"; //Initialize the path
  11.  
  12. //Get the user input and check if an input did occur
  13. if(fgets(command, sizeof(command), stdin) == NULL)
  14. {
  15. printf("Exit!n");
  16. exit(0);
  17. }
  18.  
  19. //Split the command and look store each string in parameter[]
  20. cp = strtok(command, " "); //Get the initial string (the command)
  21. strcat(parameter[0], cp); //Append the command after the path
  22. for(i = 1; i < MAX_ARG; i++)
  23. {
  24. cp = strtok(NULL, " "); //Check for each string in the array
  25. parameter[i] = cp; //Store the result string in an indexed off array
  26. if(parameter[i] == NULL)
  27. {
  28. break;
  29. cp = NULL;
  30. }
  31. }
  32. //Exit the shell when the input is "exit"
  33. if(strcmp(parameter[0], "exit") == 0)
  34. {
  35. printf("Exit!n");
  36. exit(0);
  37. }
  38.  
  39. }
  40.  
  41.  
  42. int main()
  43. {
  44.  
  45. [...]
  46.  
  47. read_command();
  48. env = NULL; //There is no environment variable
  49.  
  50. proc = fork();
  51. if(proc == -1) //Check if forked properly
  52. {
  53. perror("Error");
  54. exit(1);
  55. }
  56. if (proc == 0) //Child process
  57. {
  58. execve(parameter[0], parameter, env); //Execute the process
  59. }
  60. else //Parent process
  61. {
  62. waitpid(-1, &status, 0); //Wait for the child to be done
  63. }
  64.  
  65. [...]
  66. }
Add Comment
Please, Sign In to add comment