Prevent renaming a file from another binary on Mac OS

I work with several processes that write to the same directory. I have a dir1 / directory

My process creates the a.txt file in the dir1 / directory. However, another process creates a-temp1.txt and renames it a.txt. I have no control over another process as this code comes from the library. Can I prevent the renaming of a-temp.txt?

+5
source share
4 answers

You can, but this is unlikely to solve your problem. I strongly suspect that this is an XY problem, and almost certainly the right solution is to revise any part of this system completely, possibly by changing the file names using unique temporary files, moving to another directory or processing library usage (libraries only do what the subscribers say, and libraries are just a code). You should not try to defeat another process; you all work for one user.

All that is said, of course, you can prevent the renaming of your own file. Just deny yourself permission. You can change the file:

chmod 400 a.txt 

This means that you can read the file, but you cannot write it. However, if you already have an open file descriptor, you can continue to use it (so that you can continue to write to the file, even if there may not be another process running as the same user).

Similarly, you can change directory permissions:

 chmod 500 . 

This will prevent renaming, as the file names are stored in a directory.

0
source

You can use chflags() on the HFS + file system (Mac OS X) to set the UF_APPEND attribute. (Do a man 2 chflags .) This will allow you to add files to a file, but not delete or rename even the same user.

0
source

There you canโ€™t do anything to prevent another process from undoing. Your best hope (other than changing your program to work) is that another process doesnโ€™t complicate the renaming process too much. That is, he tries a simple approach and refuses if this fails.

In particular, you can set the UF_IMMUTABLE flag in any file, and this will not allow renaming it to replace another. You can set the flag using chflags() . Using Cocoa, you can also use [someURL setResourceValue:@YES forKey:NSURLIsUserImmutableKey error:NULL] .

Keep in mind that you cannot change the file in any other way until this flag is removed. If another process has a file rename defined, it has permission to remove the flag in the same way as your process.

Also keep in mind that a system like this is inherently subject to racial influences.

You really need to use separate names for files or separate directories or cut out a library that will not give you the control you need.

0
source

Set the immutable user flag chflags(...,uchg ). This will force another process to modify your file, unless it takes action to clear the bit. Of course, I do not know how another process will react to the fact that you put things into it, but this is not a question.

0
source

All Articles