Antonis Paragas Antonis Paragas - 7 months ago 34
C Question

Redirect console input to pipe in c

I want a functionality similar with:

cat >&5

where 5 is the pipe fd

but in c.

Is there an elegant way to achieve that or do i have to read the stdin to a buffer and write it to the pipe (or just execute the above command)?

int fd[2];
pipe(fd);

...
... (fork)
... kid is reading from fd[0]

//Parent:
//method 1
char line[255];
int got;
while((got=read(0, line, 255))>0){
write(fd[1], line, got);
}
//method 2
char cmd[25];
snprintf(cmd, 25, "cat >&%d", fd[1]);
system(cmd);


Both methods work, I just wondered if there is a better way for the task...

Answer Source

So here are a summary of the ways I managed to do it:

//Parent:
//method 1
char line[255];
int got;
while((got=read(0, line, 255))>0){
    write(fd[1], line, got);
} 

//method 2
char cmd[25];
snprintf(cmd, 25, "cat >&%d", fd[1]);
system(cmd);

//method 3
while (1) splice(0, NULL, fd[1], NULL, 255, 0);

All methods could possibly be in another thread to let parent continue.

I have added splice as well which does seem to do exactly what we are looking for.