0

I have a problem with my task. I have to change code .I have to modify the above code so that the child process redirects its standard output to a text file with the name passed by the main function argument.

#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main ()
{
    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. */
    pipe (fds);
    /* Fork a child process. */
    pid = fork ();
    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);
        /* 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");
        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;
}
  • 3
    Stackoverflow is not a "write my code for me" service. – Andrew Henle Apr 02 '19 at 11:19
  • 4
    I'm voting to close this question as off-topic because Stackoverflow is not a code-writing service. – Andrew Henle Apr 02 '19 at 11:20
  • Have you ever handled command-line arguments before? Do the signature `int main(int argc, char *argv[])` look at all familiar? If not then start by opening up your C text book on the chapter that handles command-line arguments passed to the `main` function. – Some programmer dude Apr 02 '19 at 11:20
  • 2
    Possible duplicate of [Rerouting stdin and stdout from C](https://stackoverflow.com/questions/584868/rerouting-stdin-and-stdout-from-c) – Sander De Dycker Apr 02 '19 at 11:23

0 Answers0