0

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?

granmirupa
  • 2,780
  • 16
  • 27

2 Answers2

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
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

outputlooks like this image

Fatih Altuntaş
  • 376
  • 2
  • 10