英文:
Getting errno after a write operation
问题
我有以下的Go代码,它最终会填满磁盘并因为ENOSPC
而失败(只是一个概念验证)。我如何从os.Write
返回的err
中确定它确实是因为ENOSPC
而失败的(所以我需要在写操作之后获取errno
的方法)?
package main
import (
"log"
"os"
)
func main() {
fd, _ := os.Create("dump.txt")
defer fd.Close()
for {
buf := make([]byte, 1024)
_, err := fd.Write(buf)
if err != nil {
log.Fatalf("%T %v", err, err)
}
}
}
编辑:根据@FUZxxl的建议更新了程序:
package main
import (
"log"
"os"
"syscall"
)
func main() {
fd, _ := os.Create("dump.txt")
defer fd.Close()
for {
buf := make([]byte, 1024)
_, err := fd.Write(buf)
if err != nil {
log.Printf("%T %v\n", err, err)
errno, ok := err.(syscall.Errno)
if ok {
log.Println("type assert ok")
if errno == syscall.ENOSPC {
log.Println("got ENOSPC")
}
} else {
log.Println("type assert not ok")
}
break
}
}
}
然而,我没有得到预期的结果。以下是输出:
2015/02/15 10:13:27 *os.PathError write dump.txt: no space left on device
2015/02/15 10:13:27 type assert not ok
英文:
I have the following Go code which will eventually fill the disk and fail with ENOSPC
(just a proof of concept). How can I determine from the err
returned by os.Write
that it indeed failed because of ENOSPC
(so I need a way to grab errno
after the write operation) ?
package main
import (
"log"
"os"
)
func main() {
fd, _ := os.Create("dump.txt")
defer fd.Close()
for {
buf := make([]byte, 1024)
_, err := fd.Write(buf)
if err != nil {
log.Fatalf("%T %v", err, err)
}
}
}
EDIT: Updated the program as @FUZxxl suggested:
package main
import (
"log"
"os"
"syscall"
)
func main() {
fd, _ := os.Create("dump.txt")
defer fd.Close()
for {
buf := make([]byte, 1024)
_, err := fd.Write(buf)
if err != nil {
log.Printf("%T %v\n", err, err)
errno, ok := err.(syscall.Errno)
if ok {
log.Println("type assert ok")
if errno == syscall.ENOSPC {
log.Println("got ENOSPC")
}
} else {
log.Println("type assert not ok")
}
break
}
}
}
However, I'm not getting the expected result. Here is the output:
2015/02/15 10:13:27 *os.PathError write dump.txt: no space left on device
2015/02/15 10:13:27 type assert not ok
答案1
得分: 5
文件操作通常会返回一个*os.PathError
类型的错误;将err
转换为os.PathError
类型,并使用Err
字段来检查底层原因,就像这样:
patherr, ok := err.(*os.PathError)
if ok && patherr.Err == syscall.ENOSPC {
log.Println("磁盘空间不足!")
}
英文:
File operations generally return an *os.PathError
; cast err
to os.PathError
and use the Err
field to examine the underlying cause, like this:
patherr, ok := err.(*os.PathError)
if ok && patherr.Err == syscall.ENOSPC {
log.Println("Out of disk space!")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论