Guest User

Untitled

a guest
Apr 16th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <sys/types.h>
  3. #include <unistd.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6.  
  7. #define SIZE 257
  8. int main(){
  9.  
  10. //string for user input to be read to
  11. char *line;
  12.  
  13. //string for line to be copied to, minus the null char
  14. char input[257];
  15.  
  16. //array of strings to be us:q
  17. //used for execvp
  18. char *cmd[257];
  19.  
  20. //search string for strtok
  21. char *search = " ";
  22.  
  23. //for waitpid
  24. int status;
  25.  
  26. line = malloc (SIZE+1);
  27.  
  28. pid_t pid;
  29.  
  30. //repeat infinitely
  31. while(1){
  32. printf("cmd: ");
  33. fgets(line, SIZE+1,stdin);
  34.  
  35. //get char count of user input
  36. int i=0;
  37. while(line[i] != 0){
  38. i++;
  39. }
  40.  
  41. puts(line);
  42.  
  43. //copy line to input, removing null character from end
  44. strncpy(input,line,i-1);
  45. //free(line);
  46. puts(input);
  47.  
  48. cmd[0] = strtok(input, " ");
  49.  
  50. //if the inputed command is quit, quit
  51. if (strncmp(cmd[0],"quit",4)==0){
  52. puts("bye");
  53. free(line);
  54. exit(1);
  55. }
  56.  
  57. //tokenize input into cmd
  58. i=1;
  59. while(cmd[i] = strtok(NULL, " ")){
  60. puts("success");
  61. puts(cmd[i]);
  62. i++;
  63. }
  64. pid = fork();
  65. if(pid < 0){
  66. perror("error");
  67. }
  68. else if(pid > 0){
  69. waitpid(-1, &status, 0);
  70. }
  71. else{
  72. if(execvp(cmd[0],cmd)<0){
  73. perror("exec failed");
  74.  
  75. }
  76. }
  77.  
  78. }
  79. puts("Time to quit");
  80. return 0;
  81.  
  82. }
Add Comment
Please, Sign In to add comment