Advertisement
Guest User

Untitled

a guest
Mar 31st, 2020
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.66 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <sys/types.h>
  3. #include <sys/wait.h>
  4. #include <unistd.h>
  5. #include <fcntl.h>
  6. int main (int argc, char *argv[])
  7. {
  8.     if (argc != 2)
  9.     {
  10.         printf("Blad argumentow\n");
  11.         return 1;
  12.     }
  13.  
  14.     int fds[2];
  15.     pid_t pid;
  16.  
  17.     /* Create a pipe. File descriptors for the two ends of the pipe are placed in fds. */
  18.     /* TODO add error handling for system calls like pipe, fork, etc. */
  19.     if(pipe (fds) == -1)
  20.     {
  21.         printf("Pipe error\n");
  22.         return 1;
  23.     }
  24.  
  25.     /* Fork a child process. */
  26.     pid = fork ();
  27.    
  28.     if (pid < 0)
  29.     {
  30.         return 1;
  31.     }
  32.    
  33.     if (pid == (pid_t) 0)
  34.     {
  35.     /* This is the child process. Close our copy of the write end of the file descriptor. */
  36.     close (fds[1]);
  37.     /* Connect the read end of the pipe to standard input. */
  38.     dup2 (fds[0], STDIN_FILENO);
  39.     int file_desc = open(argv[1],O_WRONLY|O_TRUNC|O_CREAT,0600);
  40.     dup2 (file_desc, STDOUT_FILENO);
  41.     /* Replace the child process with the "sort” program. */
  42.     execlp ("sort", "sort", NULL);
  43.     }
  44.  
  45.     else
  46.     {
  47.         /* This is the parent process. */
  48.         FILE* stream;
  49.         /* Close our copy of the read end of the file descriptor. */
  50.         close (fds[0]);
  51.         /* Convert the write file descriptor to a FILE object, and write to it. */
  52.         stream = fdopen (fds[1], "w");
  53.     if (stream == NULL)
  54.     {
  55.         fprintf(stderr, "Blad otwarcia strumienia\n");
  56.         return 1;
  57.     }
  58.         fprintf (stream, "This is a test.\n");
  59.         fprintf (stream, "Hello, world.\n");
  60.         fprintf (stream, "My dog has fleas.\n");
  61.         fprintf (stream, "This program is great.\n");
  62.         fprintf (stream, "One fish, two fish.\n");
  63.         fflush (stream);
  64.         close (fds[1]);
  65.         /* Wait for the child process to finish. */
  66.         waitpid (pid, NULL, 0);
  67.     }
  68.     return 0;
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement