在执行写操作后获取 errno。

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

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!")
}

huangapple
  • 本文由 发表于 2015年2月15日 03:15:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/28519245.html
匿名

发表评论

匿名网友

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

确定