How can I get the name of the three reserved file descriptors?

78 views Asked by At

I am doing a project for my school where I have to build a shell.

The thing is when I got to do the "open [file] [mode]" command for my shell, I have to keep a list of the opened files with their names, file descriptors and their mode. My problem resides in the fact that I don't know how to actually get the names of those 3 reserved file descriptors to include them in the list (since I have to do it). I know that file descriptor 0 is reserved for standard input, the 1 for standard output and the 2 for standard error output, but I think that if it's possible, I should get their names from some function or library.

I've searched in several sites of internet and I learned a lot of useful things, but I couldn't get a solution for this particular problem, so my last option is asking here and see if someone can enlighten me.

Thank you for your time.

2

There are 2 answers

0
pmg On

I think maybe you want something like this:

bool usingstdin = somelogic_using_parameters_and_configuration(argc, argv);

if (usingstdin) {
    // work with stdin
} else {
    // open file(s) at will
    // pay attention to errors
    // work with file(s)
    // close file(s)
}

and similar for stdout / stderr

Note: do not close the standard streams!

0
John Bollinger On

The thing is when I got to do the "open [file] [mode]" command for my shell, I have to keep a list of the opened files with their names, file descriptors and their mode. My problem resides in the fact that I don't know how to actually get the names of those 3 reserved file descriptors to include them in the list (since I have to do it).

Those or any file descriptors do not necessarily have names in the sense of file names on the filesystem, nor even device names. They could be pipe ends, for example. Those that are associated with a regular file at all are not associated with a particular file name, as a regular file can have more than one name on the filesystem or none. The system does not maintain a mapping from file descriptors to file names. Read the docs of fstat(), especially the description of struct stat, to find what data the system does track for each file descriptor.

You should come up with a substitute to use for these and any other file descriptors your shell inherits. Maybe a simple placeholder such as [inherited]. If you want to be a little more fancy, you can determine whether a given file descriptor is associated with a terminal device via isatty() or (with somewhat more difficulty) by interpreting its device number from a struct stat (member st_dev / st_rdev), and use this to report something different in that case. Or more generally, you could interpret device numbers to give more detailed type information -- "regular file", "terminal", "null device", etc.. But there is no good way to get a file name.