为什么os.Getwd()有时会返回EOF错误?

huangapple go评论90阅读模式
英文:

Go: Why does os.Getwd() sometimes fail with EOF

问题

package main
import "os"
import "fmt"

func main() {
_, err := os.Getwd()
if err != nil {
fmt.Println(err)
}
}

This sometimes prints an error of EOF. Does anyone know why? There's usually some os.Chdir happening before, but that doesn't error out.

GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOGCCFLAGS="-g -O2 -fPIC -m64 -pthread -fno-common"
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOOS="darwin"

go version go1.0.3

英文:
package main
import "os"
import "fmt"

func main() {
    _, err := os.Getwd()
    if err != nil {
        fmt.Println(err)
    }
}

This sometimes prints an error of EOF. Does anyone know why? There's usually some os.Chdir happening before, but that doesn't error out.

GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOGCCFLAGS="-g -O2 -fPIC -m64 -pthread -fno-common"
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOOS="darwin"

go version go1.0.3

答案1

得分: 2

这是os.Getwd中的一个错误,当工作目录不再存在时,它会返回EOF作为错误,对于不支持getwd系统调用的平台。以下是在OS X上的可重复测试案例。

package main
import "os"
import "fmt"

const DIR = "/tmp/somedir"

func main() {
    os.Remove(DIR)
    if err := os.Mkdir(DIR, 0755); err != nil {
      fmt.Println(err)
      return
    }
    if err := os.Chdir(DIR); err != nil {
      fmt.Println(err)
      return
    }
    if err := os.Remove(DIR); err != nil {
      fmt.Println(err)
      return
    }
    wd, err := os.Getwd()
    fmt.Println("err:", err)
    fmt.Println("wd:", wd)
}

输出:

err: EOF
wd: 
英文:

This is a bug in os.Getwd that causes it to return EOF as error when the working directory no longer exists, on platforms that don't support the getwd syscall. Here is a repeatable test case on OS X.

package main
import "os"
import "fmt"

const DIR = "/tmp/somedir"

func main() {
    os.Remove(DIR)
    if err := os.Mkdir(DIR, 0755); err != nil {
      fmt.Println(err)
      return
    }
    if err := os.Chdir(DIR); err != nil {
      fmt.Println(err)
      return
    }
    if err := os.Remove(DIR); err != nil {
      fmt.Println(err)
      return
    }
    wd, err := os.Getwd()
    fmt.Println("err:", err)
    fmt.Println("wd:", wd)
}

Output:

err: EOF
wd: 

huangapple
  • 本文由 发表于 2012年11月29日 04:44:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/13614048.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定