Вопрос

I am just wondering why there is no "flush" function in Perl. "perldoc -f close" says

close Closes the file or pipe associated with the filehandle, flushes the IO buffers, and closes the system file descriptor.

But the Unix manpage "man 2 close" says:

A successful close does not guarantee that the data has been successfully saved to disk, as the kernel defers writes. It is not common for a file system to flush the buffers when the stream is closed. If you need to be sure that the data is physically stored use fsync(2). (It will depend on the disk hardware at this point.)

Now, as far as I can see, there is no fsync function in Perl. Of course, Perl's close could call fsync(). But even then, the "man 2 close" says that it depends on the hardware, and I do not know what happens on other OSes. Therefore my question. I want to be sure that the buffers are flushed.

Это было полезно?

Решение

Perl's close, like C's fclose, will flush the language's IO library's buffers to the OS. The application can safely be terminated at this point.

However, this does not mean the file has been committed to disk. The machine cannot be safely turned off at this point.[1] Like the passage you claim says, fsync will get you closer to that. Remember, you have to not only sync the file, but each directory in its path.

fsync is available as IO::Handle::sync. File handles inherit from IO::Handle, so you can simply use $fh->sync. (This requires use IO::Handle; on older versions of Perl.)


  1. Unplugging the drive would not be safe either, though ejecting the media would be safe. The OS will complete its writes before allowing the ejection to happen.

Другие советы

  1. The close function in Perl is not the same as the close function in C. Perl makes certain guarantees that its C counterpart may not make (although in this matter, it does not).

  2. That quote about C's close behaviour is talking about the disk (or generally: the physical durable storage medium). Even though the data is logically saved to the filesystem from a programmers point of view, the data may still physically be in the operating systems buffer (i.e. RAM). This is of no importance unless you are trying to remove the physical medium directly after the write.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top