C Redirecting stdout to a file for process called by exec in child process
<p>I am unable to redirect STDOUT to a file.</p>

<p><strong>I have two processes.</strong> These should run for 5 seconds and then be killed.</p>

<p><strong>Process 1:</strong> redirects its STDOUT to a pipe and then prints random nubers.</p>

<p><strong>Process 2:</strong> redirects its STDIN to the pipe and its STDOUT to file. Then it calls procedure appc1 by execl(). This procedure prints to STDOUT.</p>

<p><strong>Problem:</strong> File out.txt contains the test print done by reader process, but nothing else from the appc1 procedure. If I skip the redirection and print to console, everything works fine.</p>

<p>Could it be an issue caused by killing the processes? Do I close the file too soon? Thank you very much for any advice, I am unable to solve this for quite some time.</p>

<pre><code>ret = pipe(pipefd);

if (ret == -1) {
    printf("Error creating pipe");
    exit(1);
}

reader = fork();

if (reader == 0) {  
    dup2(pipefd[0], STDIN_FILENO);

    file = fopen("out.txt", "w");
    if(file == NULL) fputs("Could not open file",stderr);

    dup2(fileno(file), STDOUT_FILENO);
    fclose(file);

    printf("Test values: %d %d\n\n", 234, 598);

    execl("appc1","appc1", NULL);
}

else {
    printf("PARENT: forking writer\n");
    writer = fork();

    if (writer == 0) {
        sleep(1);
        dup2(pipefd[1], STDOUT_FILENO);

        while (1) {
            num1 = rand() % 1000 + 1;
            num2 = rand() % 1000 + 1;
            printf("%d %d\n", num1, num2);
            sleep(1);
        }   
    }
    else {
        sleep(5);
        kill(reader, SIGUSR1);
        kill(writer, SIGUSR1);
        wait(NULL);
        exit(0);
    }
}
</code></pre>

<p>This is the code.</p>

<p>Thank you guys.</p>