openFile "/dev/null" WriteMode fails
Simon Marlow
simonmar at microsoft.com
Mon Apr 25 05:55:29 EDT 2005
On 22 April 2005 16:41, Volker Wysk wrote:
> The following program produces an "invalid operation" IOError:
>
> import IO
>
> main =
> do h <- openFile "/dev/null" WriteMode
> hPutStrLn h "bla"
> `catch` (\ioe -> putStrLn (show ioe))
>
>
> When called:
>
> /dev/null: openFile: invalid argument (Invalid argument)
>
>
> It works with AppendMode. I'm not sure if that's to be considered a
> bug. It's counter-intuitive, and openFile shouldn't fail with
> "invalid operation", since the API docs (and the Language Report) say:
>
> This operation may fail with:
>
> * isAlreadyInUseError if the file is already open and cannot be
> reopened;
> * isDoesNotExistError if the file does not exist; or
> * isPermissionError if the user does not have permission to open
> the file.
>
> I'm using GHC 6.4 on Debian Linux.
I'm going to declare this as the right behaviour. Apparently, calling
open(...,O_TRUNC) doesn't fail for /dev/null, but calling
ftruncate(..,0) on the fd does.
We don't use O_TRUNC, because if the file turns out to be locked (i.e.
in use by another Handle), then we don't want to truncate the file. We
can't do the locked test first, because that would introduce a race
condition - it requires a stat() to get the inode number, so we'd be
doing stat() followed by open(). Right now, we do open() followed by
fstat(), which doesn't have a race. We could do open(), fstat(),
open(O_TRUNC), close(), but that seems a lot of effort to go to just to
work around the problem with special files, when you can already use
AppendMode anyway.
Cheers,
Simon
More information about the Glasgow-haskell-bugs
mailing list