Advertisement
warrior98

lab10

May 16th, 2019
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.59 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<unistd.h>
  4. #include<sys/types.h>
  5. #include<string.h>
  6. #include<sys/wait.h>
  7.  
  8. char* linux_command(char query[]) {
  9.     FILE *pf;
  10.     char line[100];
  11.     char *data = (char *) malloc(sizeof(char) * 512);
  12.  
  13.     // Setup our pipe for reading and execute our command.
  14.     pf = popen(query,"r");
  15.  
  16.     // Error handling
  17.  
  18.     // Get the data from the process execution
  19.    
  20.     while(fgets(line, 100 , pf))
  21.         strcat(data, line);
  22.  
  23.     // the data is now in 'data'
  24.  
  25.     if (pclose(pf) != 0)
  26.         fprintf(stderr," Error: Failed to close command stream \n");
  27.  
  28.     return data;
  29. }
  30.  
  31. int main() {
  32.     int fd1[2], fd2[2];
  33.    
  34.     if (pipe(fd1)==-1) {
  35.         fprintf(stderr, "Pipe Failed" );
  36.         return 1;
  37.     }
  38.     if (pipe(fd2)==-1) {
  39.         fprintf(stderr, "Pipe Failed" );
  40.         return 1;
  41.     }
  42.    
  43.     pid_t p = fork();
  44.    
  45.     if(p > 0) {
  46.         char nume[100];
  47.        
  48.         printf("Introduceti numele utilizatorului: ");
  49.         scanf("%s", nume);
  50.        
  51.         close(fd1[0]);
  52.        
  53.         write(fd1[1], nume, strlen(nume)+1);
  54.         close(fd1[1]);
  55.        
  56.         wait(NULL);
  57.        
  58.         close(fd2[1]);
  59.        
  60.         char informations[300];
  61.         read(fd2[0], informations, 300);
  62.        
  63.         printf("Informatii despre utilizatorul ales:\n%s\n", informations);
  64.         close(fd2[0]);
  65.     }
  66.     else if (p == 0) {
  67.         close(fd1[1]);
  68.        
  69.         char query[200] = "finger ";
  70.         char nume[100];
  71.        
  72.         read(fd1[0], nume, 100);
  73.        
  74.         strcat(query, nume);
  75.        
  76.         close(fd1[0]);
  77.         close(fd2[0]);
  78.        
  79.         char *response = linux_command(query);
  80.        
  81.         write(fd2[1], response, strlen(response)+1);
  82.         close(fd2[1]);
  83.  
  84.         exit(0);
  85.     }
  86.    
  87.     return 0;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement