Advertisement
STANAANDREY

redirect ls output linux to parent

Nov 2nd, 2024
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.90 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <signal.h>
  4. #include <unistd.h>
  5. #include <string.h>
  6. #include <sys/types.h>
  7. #include <sys/wait.h>
  8. #include <sys/stat.h>
  9. #include <fcntl.h>
  10.  
  11. #define BUFF_SIZE (1 << 10)
  12.  
  13. int main(int argc, char *argv[]) {
  14.     int pbuff[2];
  15.     if (pipe(pbuff)) {
  16.         perror("pipe");
  17.         exit(1);
  18.     }
  19.     pid_t pid = fork();
  20.     if (pid == -1) {
  21.         perror("");
  22.         exit(-1);
  23.     }
  24.     if (pid == 0) {//kid
  25.         close(pbuff[0]);
  26.         dup2(pbuff[1], STDOUT_FILENO);
  27.         execlp("ls", "ls", "-l", NULL);
  28.         fprintf(stderr, "execl error\n");
  29.         exit(1);
  30.     }
  31.     close(pbuff[1]);
  32.     char s[BUFF_SIZE];
  33.     memset(s, 0, BUFF_SIZE);
  34.     int cnt = 0;
  35.     while (read(pbuff[0], &s, BUFF_SIZE)) {
  36.         cnt += strlen(s);
  37.     }
  38.     printf("Cnt: %d\n", cnt);
  39.     close(pbuff[0]);
  40.     int stat;
  41.     wait(&stat);
  42.     return 0;
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement