Truncating a file while it's being used (Linux)

后端 未结 13 2170
名媛妹妹
名媛妹妹 2020-12-05 01:54

I have a process that\'s writing a lot of data to stdout, which I\'m redirecting to a log file. I\'d like to limit the size of the file by occasionally copying the current

13条回答
  •  悲哀的现实
    2020-12-05 02:35

    In Linux (actually all unicies) files are created when they are opened and deleted when nothing holds a reference to them. In this case the program that opened it and the directory it was opened 'in' hold references to the file. When the cp program wants to write to the file it gets a reference to it from the directory, writes a length of zero into the metadata stored in the directory (this is a slight simplification) and gives up the handle. Then the original program, still holding the original file handle, writes some more data to the file and saves what it thinks the length should be.

    even if you where to delete the file from the directory the program would continue to write data to it (and use up disc space) even though no other program would have any way of referencing it.

    in short once the program has a reference (handle) to a file nothing you do is going to change that.

    there are in theory ways of modifying the programs behavior by setting LD_LIBRARY_PATH to include a program that intercepts all the file access system calls. I recall seeing something like this somewhere though cant recall the name.

提交回复
热议问题