linux - how to use flock between C program and shell script -


i have shell script , c program

    #!/bin/bash     in `seq 1 10000`         (flock -x 200                   // 200?        ./taska     ) 200> lockfile     done 

in c program, related code snippets are:

    int fd = open("lockfile", o_wronly|o_creat); // permission should put here?     for(i=0;i<10000;i++){       if(fd==-1)             printf("open file fails\n");        if(flock(fd, lock_ex)==0 ){      // lock file             taskb(); // here want             }        if (flock(fd, lock_un)==0)  // after finishing tasks, unlock       {             printf("c unlock\n");       }      } 

i want run shell script , c program on same host , hope can run taska , taskb @ alternately, in different time i'm not familiar flock, there permission problems or open file failures

for example, if run c program , let finish , run again, "open file failure" , permission is

---xr-x--t 1 esolve 200036    0 may  6 02:18 lockfile 

how modify scripts , code? thanks!

the 200 in shell script file descriptor — see manual page flock(1).

your problem file permissions open(2) takes 3 arguments when include o_creat; third argument should permissions on file. when don't specify third argument, quasi-random value chosen you. takes lot of analysis detect problem because open(2) has signature:

#include <fcntl.h>  int open(const char *path, int oflag, ...); 

it variable-length argument list function, using 2 arguments ok of time, except when o_creat specified needs third argument.


Comments