My C/C++ program takes a file from the command line as an argument. Reading data from ‘regular files’ is no problem/general programming task, but when the file comes from a ‘device pipe’ such as /dev/fd/63 it causes my program to crash.
To reproduce:
from your friendly neighborhood bash shell supply a ‘device pipe’ as a file to your application. Your app should try to read the file contents into a buffer.
./yourapp <(echo ‘Hello World!’); # /dev/fd/xx containing output from echo command.
Note the above command is not redirecting the standard input of the application and that is not the intended result..
I don’t think that a lot of people know this will crash their application. The application ‘seed’ from the Gnome project uses glib to do its I/O but it can read from these files just fine. The command ‘cat’ can also handle this situation gracefully. Why is it when I try to read the contents of that named pipe like a regular file my application gets the crash bug?
EDIT: relavent code section
#include <stdio.h>
int main(int argc, char **argv) {
FILE *file;
char *buffer;
unsigned long fileLen;
//Open file
file = fopen(argv[1], "rb");
if (!file) return -1;
//Get file length
fseek(file, 0, SEEK_END);
fileLen=ftell(file);
fseek(file, 0, SEEK_SET);
//Allocate memory
buffer=(char *)malloc(fileLen+1);
if (!buffer){
fprintf(stderr, "Memory error!");
fclose(file);
return -2;
}
//Read file contents into buffer
fread(buffer, fileLen, 1, file);
fclose(file);
fprintf(stdout, "Size: %i", fileLen);
free(buffer);
}
Can’t call fseek on a pipe. The code shows that I was indeed trying to do such a foolish thing.