Advertisement
Guest User

as

a guest
May 25th, 2015
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*gcc uebung05.c -Wall -ansi -o uebung05.out*/
  2. #include <sys/types.h>
  3. #include <stdio.h>
  4. #include <unistd.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7. #include <fcntl.h>
  8. #include <sys/stat.h>
  9.  
  10. char* mystdin(){
  11.   int  strlen = 4;                            /*string lenght*/
  12.   char *str = malloc(strlen * sizeof(char));  /*input string*/
  13.   char c;                                     /*new char*/
  14.   int counter = 0;                            /*position neuer char*/
  15.   while((c = getchar()) != '\n'){             /*zeile einlesen*/
  16.     if(counter >= strlen)                     /*falls länge überschritten*/
  17.       str = realloc(str, (strlen += 4) * sizeof(char)); /* mache platz für 4 neue Zeichen*/
  18.     str[counter++] = c;                       /*füge neuen cahr hinzu*/
  19.   }
  20.   str = realloc(str, (counter++) * sizeof(char));
  21.   str[counter-1] = '\0';                      /*beende string*/
  22.   return str;
  23. }
  24.  
  25. int main(void)
  26. {
  27.   pid_t pid, wpid;
  28.   int status = 0;
  29.   int newSTDIN = 0;
  30.   int newSTDOUT = 0;
  31.   char* input = NULL;
  32.   char* output = NULL;
  33.   char* cmd;
  34.   char* params;
  35.   char* lcmd=mystdin();
  36.   printf("lcmd:\"%s\"\n", lcmd);
  37.   char* temp=strchr(lcmd,'<');
  38.   if(temp!=NULL){
  39.       input=lcmd;
  40.       *(temp-1)='\0';
  41.       temp++;
  42.       cmd=temp;
  43.   }
  44.   else
  45.       cmd=lcmd;
  46.   output=strchr(cmd,'>');
  47.   if(output!=NULL){
  48.       *output='\0';
  49.       output++;
  50.   }
  51.   while(*output==' ')
  52.     *output++;
  53.   while(*cmd==' ')
  54.     *output++;
  55.   params=strchr(cmd,' ');
  56.   if(params!=NULL){
  57.       *params='\0';
  58.       params++;
  59.   }
  60.   printf("input:\"%s\"\n", input);
  61.   printf("output:\"%s\"\n", output);
  62.   printf("cmd:\"%s\"\n", cmd);
  63.   printf("params:\"%s\"\n", params);
  64.   if((pid=fork()) < 0)
  65.     perror("fork error");
  66.     else if(pid == 0) {
  67.           if(input != NULL){
  68.             newSTDIN = open(input, O_RDONLY);
  69.                 dup2(newSTDIN, STDIN_FILENO);
  70.                 close(newSTDIN);
  71.           }
  72.           if(output != NULL){
  73.             newSTDOUT = open(output, O_RDONLY);
  74.                 dup2(newSTDOUT, STDIN_FILENO);
  75.                 close(newSTDOUT);
  76.           }
  77.           return execlp(cmd,cmd,params,NULL);
  78.     }else {
  79.       wpid = wait(&status);
  80.       printf("Exit status of %d was %d (%s)\n", (int)wpid, status, (status == 0)? "OK" : "ERROR");
  81.       /*free?*/
  82.     }
  83.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement