There is a folder which is being created within another folder in my home directory, and I want to be able to analyse the contents of this folder, however, I have a problem: as the folder is created, it is then immediately deleted by the same program that creates it. Is there any way that I can allow it to create the folder, but then not to delete it? I am running Ubuntu GNOME 15.10 with GNOME 3.18.
1 Answers
There are no permission settings that can do this, even using ACLs, but you can have a race with the program, using inotifywait:
In one terminal, I ran:
while sleep 0.5; do if mkdir foo/bar; then echo foo; rmdir foo/bar; fi; done
As you can see, this creates a directory, echoes a message and removes the directory - all of which happens very quickly by human standards.
And in another:
while true
do
if inotifywait -e create foo
then
chmod -w foo
if [[ -d foo/bar ]]
then
break
else
chmod +w foo
fi
fi
done
This command waits for creation of anything in foo, then removes write permissions from foo, and tests if it was in time for catching the sub directory. If not, it adds back the write permission, and starts again.
After waiting a bit:
foo
foo
foo
foo
foo
foo
foo
foo
foo
foo
foo
foo
foo
foo
foo
foo
foo
foo
foo
foo
foo
foo
foo
foo
foo
foo
rmdir: failed to remove ‘foo/bar’: Permission denied
mkdir: cannot create directory ‘foo/bar’: File exists
mkdir: cannot create directory ‘foo/bar’: File exists
mkdir: cannot create directory ‘foo/bar’: File exists
mkdir: cannot create directory ‘foo/bar’: File exists
This is relying on a race condition, so whether you can catch it is a matter of luck.
foo/bar is the directory that the program makes. If you don't know the name of it, you can try other ways:
ensure that there's nothing else in the directory, so when a subdirectory is created,
foo/is non-empty. Some tests for non-empty directory are available in this U&L post:shopt -s nullglob if [ -n "$(ls -A foo/)" ] then breakThis worked fast enough.
read the name of the created directory from
inotifywait's output:if dir=$(inotifywait -e create --format '%f' foo) then chmod -w foo if [[ -d foo/$dir ]]This didn't work (yet) for me; the overhead of creating subshell seems to make it just sufficiently slow enough for the other loop to win each time. Maybe coded in C using the
inotifyAPI, this could work.