I am writing a small shell in C that runs on Linux. Because there are a lot of dups involved, I would like to ask if there is a way to print what is inside position 0. For example if I call dup2(file_name,0) is there a way to print the file_name so I can use it for debugging?
Asked
Active
Viewed 157 times
2 Answers
1
You can't get the filename from dup2. As you can read here it only returns a int
value:
int dup2(int fildes, int fildes2);
What you can do in Linux is:
You can use readlink on /proc/self/fd/NNN where NNN is the file descriptor. This will give you the name of the file as it was when it was opened [here]
Or something more creative is creating a struct
where you can assosiate the fildes
to a filename
.
Something like this:
struct Files{
int fildes;
char filename[50];
} files;
If you have more then one just create an array and take the one you need every time; in such a way you can always map it with a filename
.

Community
- 1
- 1

granmirupa
- 2,780
- 16
- 27
-
Note that not all versions of Unix support the `/proc` file system. – Jonathan Leffler May 07 '17 at 22:02
-
@JonathanLeffler but this answer is Linux-specific. The OP asked for linux. Do you think I should in anycase write a note? – granmirupa May 07 '17 at 22:16
-
I missed that Linux was mentioned in the question, even though it's not in the tags. You're fine, then. – Jonathan Leffler May 07 '17 at 23:03
1
If you are using linux operating system,you can show your file description table easily every process on linux stored /proc/ directory by their process id, fd folder show file description table of process e.g.
ls -l /proc/1405/fd

Fatih Altuntaş
- 376
- 2
- 10