patterncMinor
Simple file locking wrapper command in C
Viewed 0 times
filesimplewrapperlockingcommand
Problem
A simple command that wraps another command, locking a file first. It is similar to
Anything fishy? Bogus? Wrong? Anything that can be improved (besides adding options like
flock, just simpler.#include
#include
#include
#include
#include
#include
void attemptLock(const char *lockFileName)
{
int fd = open(lockFileName, O_CREAT | O_WRONLY, 0666);
if (!fd || flock(fd, LOCK_EX))
warn("Cannot lock %s", lockFileName);
}
int main(int argc, char *argv[])
{
if (argc < 3)
errx(EXIT_FAILURE, "Not enough arguments.\nUsage: %s LOCKFILENAME COMMAND...\n", argv[0]);
attemptLock(argv[1]);
argv += 2; // Skip our own command name and LOCKFILENAME.
execvp(argv[0], argv);
err(EXIT_FAILURE, "Cannot execute %s", argv[0]);
}Anything fishy? Bogus? Wrong? Anything that can be improved (besides adding options like
-h)?Solution
Besides reinventing the wheel the things I'm concerned about are:
fails, or if you can't get the lock (or the call was interrupted), I
would expect the wrapper to exit instead,
check for that separately and give an error message for that,
I believe?
- the
warninattemptLock, because if either creating the lock file
fails, or if you can't get the lock (or the call was interrupted), I
would expect the wrapper to exit instead,
- the return value of
open, which might very well be negative, so just
check for that separately and give an error message for that,
- the return value of
flock, where you should handleEINTRin a loop
I believe?
Context
StackExchange Code Review Q#80227, answer score: 2
Revisions (0)
No revisions yet.