3

Why would f.Write() not return any error if I remove the file before I write?

package main

import (
    "fmt"
    "os"
    "time"
)

func main() {
    f, err := os.Create("foo")
    if err != nil {
        panic(err)
    }

    if err := os.Remove("foo"); err != nil {
        panic(err)
    }

    if _, err := f.Write([]byte("hello")); err != nil {
        panic(err) // would expect panic here
    }

    fmt.Println("no panic?")
}

http://play.golang.org/p/0QllIB6L9O

mattes
  • 8,936
  • 5
  • 48
  • 73
  • 3
    See: http://stackoverflow.com/questions/9164925/ –  Dec 17 '15 at 01:26
  • That makes sense. Also found this: http://unix.stackexchange.com/questions/146929/how-can-a-log-program-continue-to-log-to-a-deleted-file – mattes Dec 17 '15 at 01:45

1 Answers1

1

Apparently this is expected.

When you delete a file you really remove a link to the file (to the inode). If someone already has that file open, they get to keep the file descriptor they have. The file remains on disk, taking up space, and can be written to and read from if you have access to it.

Source: https://unix.stackexchange.com/questions/146929/how-can-a-log-program-continue-to-log-to-a-deleted-file

Community
  • 1
  • 1
mattes
  • 8,936
  • 5
  • 48
  • 73
  • 1
    This will behave differently on Windows. I think Remove will fail. – kostya Dec 17 '15 at 02:27
  • @kostya Yes, it does. You get `panic: remove foo: The process cannot access the file because it is being used by another process.` – abm Dec 17 '15 at 03:06