Shell – Prevent already running process to write to an existing file

access-controldebianfileslinuxshell-script

I have a process P which writes contents to a file F. I need to be able to dynamically enable/disable P to write to F. I tried changing the permissions for the user/group but this requires the process to be restarted(in fact the whole system).
In the end I should be able to execute a "script" which does the following:

EnablePWriteF  
sleep 10  
DisablePWriteF  

and as a result P will be able to write for the first 10 seconds and not after that. I am using Debian distibution.

Is this possible?

Update:
The real use case is that I am trying to filter a given process to write to a specific device file /dev/fb0
I have two processes which are writing to that file and I want to be able to determine exactly one of the two which is allowed to write to that file at a given moment without having to kill/stop the processes.

Best Answer

At least on my version of Linux, it looks like you may be able to use mandatory locks. I've only tested it with /dev/null, but I can't see any reason why it wouldn't work with other devices like your frame buffers:

As root:

mount -t tmpfs -o mand locked-fb some-dir
cp -a /dev/fb0 some-dir/fb0-for-process-A
cp -a /dev/fb0 some-dir/fb0-for-process-B
chmod g+s some-dir/fb0-for-process-[AB] # enable mand-lock

Then for instance, using perl and the File::FcntlLock module (or do it directly in C):

#! /usr/bin/perl
use File::FcntlLock;

$l = new File::FcntlLock;
$l->l_type(F_RDLCK);

open my $fba, '<', 'some-dir/fb0-for-process-A' or die$!;

sleep 10; # writing OK
$l->lock($fba, F_SETLK); # writing blocked on fb0-for-process-A

sleep 10;
exit; # lock now released (or do an explicit unlock)

Have one process open the fb0 device via the fb0-for-process-A file, and the other one via fb0-for-process-B and apply locking to both files to decide which process may write at a given time.

Related Question