Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <sys/types.h>
- #include <sys/wait.h>
- #include <unistd.h>
- #include <fcntl.h>
- int main (int argc, char *argv[])
- {
- if (argc != 2)
- {
- printf("Blad argumentow\n");
- return 1;
- }
- int fds[2];
- pid_t pid;
- /* Create a pipe. File descriptors for the two ends of the pipe are placed in fds. */
- /* TODO add error handling for system calls like pipe, fork, etc. */
- if(pipe (fds) == -1)
- {
- printf("Pipe error\n");
- return 1;
- }
- /* Fork a child process. */
- pid = fork ();
- if (pid < 0)
- {
- return 1;
- }
- if (pid == (pid_t) 0)
- {
- /* This is the child process. Close our copy of the write end of the file descriptor. */
- close (fds[1]);
- /* Connect the read end of the pipe to standard input. */
- dup2 (fds[0], STDIN_FILENO);
- int file_desc = open(argv[1],O_WRONLY|O_TRUNC|O_CREAT,0600);
- dup2 (file_desc, STDOUT_FILENO);
- /* Replace the child process with the "sortβ program. */
- execlp ("sort", "sort", NULL);
- }
- else
- {
- /* This is the parent process. */
- FILE* stream;
- /* Close our copy of the read end of the file descriptor. */
- close (fds[0]);
- /* Convert the write file descriptor to a FILE object, and write to it. */
- stream = fdopen (fds[1], "w");
- if (stream == NULL)
- {
- fprintf(stderr, "Blad otwarcia strumienia\n");
- return 1;
- }
- fprintf (stream, "This is a test.\n");
- fprintf (stream, "Hello, world.\n");
- fprintf (stream, "My dog has fleas.\n");
- fprintf (stream, "This program is great.\n");
- fprintf (stream, "One fish, two fish.\n");
- fflush (stream);
- close (fds[1]);
- /* Wait for the child process to finish. */
- waitpid (pid, NULL, 0);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement