B.Li B.Li - 23 days ago 6
C Question

using a child process to read input?

I'm trying to use a child process to count words from console input (what I type in UNIX). Here is my code:

int main(){
int pipe1[2];
int child_value;

pipe(pipe1);
child_value= fork();

if(child_value > 0){
/*parent*/
int word_count;
dup2(STDIN_FILENO, pipe1[0]);

close(pipe1[0]);

scanf("%d", &word_count);
printf("%d\n", word_count);
} else if (child_value == 0) {
/*child*/
dup2(pipe1[1], STDOUT_FILENO);
close(pipe1[1]);
execl("/usr/bin/wc", "wc", "-w", NULL);
err(EX_OSERR, "exec error");

} else err(EX_OSERR, "fork error");

return 0;
}


The output displayed on my console is always 0 disregarding what I type into the console, and I always get an error saying:

wc: standard input: Input/output error

Answer

As noted in comments:

When you use dup2() or dup() to map one end of a pipe to standard input or standard output, it is almost invariably correct to close both ends of the pipe afterwards. The exceptions are very few and far between; you will know when you need to avoid closing both ends of the pipe. However, that isn't the direct cause of your problem.

Compare: dup2(STDIN_FILENO, pipe1[0]); and dup2(pipe1[1], STDOUT_FILENO);. They should both list the standard file number as the second argument.

#include <err.h>
#include <fcntl.h>
#include <stdio.h>
#include <sysexits.h>
#include <unistd.h>

int main(void)
{
    int pipe1[2];
    int child_value;

    pipe(pipe1);
    child_value = fork();

    if (child_value > 0)
    {
        /*parent*/
        int word_count;
        dup2(pipe1[0], STDIN_FILENO);

        close(pipe1[0]);
        close(pipe1[1]);

        scanf("%d", &word_count);
        printf("%d\n", word_count);
    }
    else if (child_value == 0)
    {
        /*child*/
        dup2(pipe1[1], STDOUT_FILENO);
        close(pipe1[1]);
        close(pipe1[0]);
        execl("/usr/bin/wc", "wc", "-w", NULL);
        err(EX_OSERR, "exec error");
    }
    else
        err(EX_OSERR, "fork error");

    return 0;
}

Example output (program xx19):

$ ./xx19
So she went into the garden
to cut a cabbage-leaf
to make an apple-pie
and at the same time
a great she-bear coming down the street
pops its head into the shop
What no soap
So he died
and she very imprudently married the Barber
and there were present
the Picninnies
and the Joblillies
and the Garyulies
and the great Panjandrum himself
with the little round button at top
and they all fell to playing the game of catch-as-catch-can
till the gunpowder ran out at the heels of their boots
90
$

(You can search on Google for 'Panjandrum' to find out where that nonsense prose comes from.)

Comments