[go-nuts] Linux File descriptor question in golang

458 views
Skip to first unread message

Homer Li

unread,
Jul 21, 2016, 6:03:06 AM7/21/16
to golan...@googlegroups.com
Could I get file path from the file descriptor number ? 
OS : Linux
How to write in golang ?

Thanks.

--
Best Regards
Homer Li

Konstantin Khomoutov

unread,
Jul 21, 2016, 7:09:49 AM7/21/16
to Homer Li, golan...@googlegroups.com
On Thu, 21 Jul 2016 18:02:53 +0800
Homer Li <01ja...@gmail.com> wrote:

> Could I get file path from the file descriptor number ?
> OS : Linux
> How to write in golang ?

I'm afraid, you can't.

But as usually in such cases, I have an imminent question: what initial
problem are you trying to solve?

Alex Bligh

unread,
Jul 21, 2016, 7:38:16 AM7/21/16
to Homer Li, Alex Bligh, golan...@googlegroups.com

> On 21 Jul 2016, at 11:02, Homer Li <01ja...@gmail.com> wrote:
>
> Could I get file path from the file descriptor number ?
> OS : Linux
> How to write in golang ?

On Linux (and indeed most if not all POSIX like systems)
one cannot get a file path from the file descriptor number.
This is irrespective of programming language used.

Consider what happens if you open a file, then unlink it.
Or open it then rename it. Or open a file with multiple links
to it. Etc.

--
Alex Bligh




Peter Waller

unread,
Jul 21, 2016, 8:57:15 AM7/21/16
to Alex Bligh, Homer Li, golang-nuts
On 21 July 2016 at 12:37, Alex Bligh <al...@alex.org.uk> wrote:
On Linux (and indeed most if not all POSIX like systems)
one cannot get a file path from the file descriptor number.
This is irrespective of programming language used.

While your statement is true generally, it is actually possible so long as the file descriptor refers to an existing file. Consider:

$ fd2path < main.go 
/home/pwaller/.local/src/github.com/pwaller/fd2path/main.go

Code:

package main

import (
"fmt"
"log"
"os"
)

func main() {
fd := os.Stdin.Fd()
fileName, err := os.Readlink(fmt.Sprint("/proc/self/fd/", fd))
if err != nil {
log.Fatal(err)
}
fmt.Println(fileName)
}


Reply all
Reply to author
Forward
0 new messages