5
\$\begingroup\$

A simple command that wraps another command, locking a file first. It is similar to flock, just simpler.

#include <stddef.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/file.h>
#include <err.h>
#include <stdlib.h>
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)?

200_success
145k22 gold badges190 silver badges478 bronze badges
asked Feb 11, 2015 at 7:32
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Besides reinventing the wheel the things I'm concerned about are:

  • the warn in attemptLock, 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 handle EINTR in a loop I believe?
answered Feb 11, 2015 at 17:32
\$\endgroup\$
1
  • \$\begingroup\$ Once again shows how good it is to have code reviewed. The warn instead of err was intentional because of support for a specific version of Cygwin which has issues with successfully locking, but there should at least have been a comment for explaining the unexpected warn instead of err. And the other two issues that you've found are real bugs. So, thanks a lot! \$\endgroup\$ Commented Feb 12, 2015 at 5:46

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.