Reputation: 2287
I have a shell script and a c program
#!/bin/bash
for i in `seq 1 10000`
do
(flock -x 200 // what is 200?
./taskA
) 200> lockfile
done
in the C program, related code snippets are:
int fd = open("lockfile", O_WRONLY|O_CREAT); // what permission should I put here?
for(i=0;i<10000;i++){
if(fd==-1)
printf("open file fails\n");
if(flock(fd, LOCK_EX)==0 ){ // lock the file
taskB(); // here is what I want to do
}
if (flock(fd, LOCK_UN)==0) // after finishing those tasks, unlock it
{
printf("C unlock\n");
}
}
I want to run the shell script and C program on the same host
and I hope they can run taskA
and taskB
at alternately, in different time
but I'm not familiar with flock, so there are some permission problems or open file failures
for example, if I run the C program and let it finish and then run it again, I get "open file failure" and the permission is
---xr-x--T 1 esolve 200036 0 May 6 02:18 lockfile
how to modify the scripts and code? thanks!
Upvotes: 2
Views: 3704
Reputation: 754530
The 200 in the shell script is a file descriptor — see the manual page for flock(1)
.
Your problem with the file permissions is that open(2)
takes 3 arguments when you include O_CREAT
; the third argument should be the permissions on the file. When you don't specify the third argument, you get some quasi-random value chosen for you. It takes a lot of analysis to help you detect that problem because open(2)
has the signature:
#include <fcntl.h>
int open(const char *path, int oflag, ...);
It is a variable-length argument list function, so using just two arguments is OK most of the time, except that when O_CREAT
is specified it needs the third argument.
Upvotes: 2