JimR
JimR

Reputation: 2225

Reading input from a particular file descriptor

If I know that input to my program will come from a file descriptor with a (non standard) ID, how do I read from it?

For example, if I need to read from a file descriptor with the ID of 3, how do I do it?

Also, is there an easy way to test this in BASH without having to create another program and piping?

This is what I've got so far:

char buffer[100];
FILE* fd = fdopen(3, "r");
fgets(buffer, sizeof buffer, fd);
sscanf(buffer, "%d", &whatever);

It compiles but gets a segmentation error when I run it. I looked at it in gdb and it gets stuck at the fgets, so I guess I'm doing something wrong? Possibly cause there's no end of file coming in on file descriptor 3 when I'm testing (again, would be nice if I could properly test this in BASH).

Upvotes: 2

Views: 916

Answers (2)

pmg
pmg

Reputation: 108988

In bash, assuming your executable is "a.out", do

./a.out 3< testfile

to have testfile assigned to file descriptor 3

The same invocation works in bash, sh, zsh, ...
It does not work in csh, tcsh, ...

Upvotes: 2

Philip
Philip

Reputation: 5917

If you don't previously open it, there is no file with file descriptor 3. fdopen() fails and hence fd is NULL, resulting in a segmentation fault when trying fgets() on it.

Always check the return value of your function calls.

Upvotes: 2

Related Questions