java - Detect file deletion while using a FileOutputStream -
i have created java process writes plain text file , java process consumes text file. 'consumer' reads deletes text file. sake of simplicity, not use file locks (i know may lead concurrency problems).
the 'consumer' process runs every 30 minutes crontab
. 'producer' process redirects whatever receives standard input text file. testing - in future, 'producer' process write text file itself.
the 'producer' process opens fileoutputstream
once , keeps writing text file usign output stream. problem when 'consumer' deletes file. since i'm in unix environment, situation handled 'gracefully': 'producer' keeps working if nothing happened, since inode
of file still valid, file can no longer found in file system. this thread provides way handle situation using c. since i'm using java, portable , therefore hides platform-specific features, i'm not able use solution presented there.
is there portable way in java detect when file deleted while fileoutputstream
still open?
this isn't robust way processes communicate, , best can advise stop doing that.
as far know there isn't reliable way c program detect when file being written unlinked, let alone java program. (the accepted answer you've linked to can poll directory entry see if it's still there; don't consider sufficiently robust).
as you've noticed, unix doesn't consider abnormal open file unlinked (indeed, it's established practice create named tempfile, grab filehandle, delete directory other processes can't @ it, before reading , writing).
if must use files, consider having consumer poll directory. have .../pending/
directory files in process of being written , .../inbox/
files ready processing.
- producer creates new uniquefilename (e.g. uuid) , writes new file
pending/
. - after closing file, producer moves file
inbox/
-- long both dirs on same filesystem, relink, file never incomplete ininbox/
. - consumer looks files in
inbox/
, reads them , deletes when done.
you can enhance more directories if there multiple consumers, there's no immediate need.
but polling files/directories bit fragile. consider database or message queue.
Comments
Post a Comment