Reputation: 12387
I can redirect the output of a process to a file
./prog > a.txt
But if I delete a.txt and do not restart prog, then no more output will get into a.txt. The same is the case if I use the append-redirect >>.
Is there a way to make my redirection recreate the file when it is deleted during the runtime of prog?
Redirection is part of the OS I think and not of prog. So maybe there are some tools or settings.
Thanks!
Upvotes: 1
Views: 401
Reputation: 577
You can use gdb
to redirect the output of program to file when original file is deleted.
Refer to this post.
For later references, I give the only excerpt from the post:
/proc/<pid>/fd
.gdb
.gdb
session.gdb
calls.Examples
Suppose that PID of program is 19080 and file descriptor of deleted file is 2.
gdb attach 19080
ls -l /proc/19080/fd
gdb> p close(2)
$1 = 0
gdb> p fopen("/tmp/file", "w")
$2 = 20746416
(gdb) p fileno($2)
$3 = 7
gdb> quit
N.B.: If data of the deleted file is required, recover the deleted text file before closing the file handle:
cp -pv /proc/19080/fd/2 recovered_file.txt
Upvotes: 1
Reputation: 72266
At the OS level, a file is made up of many components:
All these are linked and the OS keeps their booking.
If you delete the file while it is open by another application (the redirect operator >
keeps it open until ./prog
completes), only the name is removed from the directory. The other pieces of the puzzle are still there and they keep working until the last application that keeps the file open closes it. This is when the file content is discarded on the storage medium.
If you delete the file, while ./prog
keeps running and producing output the file grows and uses space on the storage medium but it cannot be open again because there is no way to access it. Only the programs that have it already open when it was deleted can still access the file until they close it.
Even if you re-create the file, it is a different file that happens to have the same name as the deleted one. ./prog
is not affected, its output goes to the old, deleted file.
When its output is redirected, apart from restarting ./prog
, there is no way to persuade it to store its output in a different file when a.txt
is deleted.
There are several ways to make this happen if ./prog
writes itself into a.txt
(they all require changing the code of ./prog
).
Upvotes: 3