Advertisement
Guest User

hw

a guest
Nov 23rd, 2014
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.36 KB | None | 0 0
  1. #include <sys/wait.h>
  2. #include <iostream>
  3. #include <unistd.h>
  4. #include <stdio.h>
  5. #include <cstdlib>
  6. #include <string.h>
  7.  
  8. using namespace std;
  9.  
  10. char** getlastline(int& l){
  11.     char** ans=NULL;
  12.     char c;
  13.     l=0;
  14.     while(true){
  15.         cin>>c;
  16.         while (c==' ') cin>>c;
  17.         if ((c=='\n') || (c==-1))
  18.             break;
  19.         char* word;
  20.         int wlength=0;
  21.         while ((c!=' ') && (c!='\n') && (c!=-1)){
  22.             if (wlength==0)
  23.                 word=(char *)malloc(sizeof(char));
  24.             else
  25.                 word=(char *)realloc(word, (wlength+1)*sizeof(char));
  26.             word[wlength++]=c;
  27.             cin>>c;
  28.         }
  29.         if (wlength!=0){
  30.             if (l==0)
  31.                 ans=(char**)malloc(sizeof(char*));
  32.             else
  33.                 ans=(char**)realloc(ans, (l+1)*sizeof(char));
  34.             ans[l++]=(char*)malloc((wlength+1)*sizeof(char));
  35.             strcpy(ans[l-1], word);
  36.         }
  37.         cout<<word<<endl;
  38.         free(word);
  39.     }
  40.     if (l!=0){
  41.         ans=(char**)realloc(ans, (l+1)*sizeof(char));
  42.         ans[l++]=(char*)malloc(sizeof(char));
  43.         ans[l-1]=NULL;
  44.     }
  45.     return ans;
  46. }
  47.  
  48. int main(){
  49.     int n;
  50.     while (true){
  51.         int l=0;
  52.         char** s=getlastline(l);
  53.         if (l==0)
  54.             return 1;
  55.         n=fork();
  56.         int status;
  57.         if (n==0){
  58.             if (execvp(s[0], s) == -1){
  59.                 perror("exec ");
  60.                 return 1;
  61.             }
  62.         }
  63.         else
  64.             wait(&status);
  65.         if (!WIFEXITED(status) || WEXITSTATUS(status)){
  66.             cout<<"It all went wrong!";
  67.             return 1;
  68.         }
  69.         for (int i=0; i<l; i++)
  70.             free(s[i]);
  71.         free(s);
  72.     }
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement