简体   繁体   English

如何在C程序和Shell脚本之间使用flock

[英]how to use flock between C program and shell script

I have a shell script and ac program 我有一个shell脚本和一个ac程序

    #!/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: 在C程序中,相关的代码段为:

    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 我想在同一主机上运行Shell脚本和C程序,希望它们可以在不同的时间交替运行taskAtaskB ,但是我不熟悉flock,因此存在一些权限问题或打开文件失败

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 例如,如果我运行C程序并使其完成然后再次运行,则显示“打开文件失败”,并且权限为

---xr-x--T 1 esolve 200036    0 May  6 02:18 lockfile

how to modify the scripts and code? 如何修改脚本和代码? thanks! 谢谢!

The 200 in the shell script is a file descriptor — see the manual page for flock(1) . Shell脚本中的200是文件描述符-请参见手册页flock(1)

Your problem with the file permissions is that open(2) takes 3 arguments when you include O_CREAT ; 您的文件权限问题是,当您包含O_CREAT时, open(2)需要3个参数; 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: 由于open(2)具有签名,因此需要大量分析来帮助您检测到该问题:

#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. 它是一个可变长度的参数列表函数,因此大多数情况下只使用两个参数是可以的,除了指定O_CREAT时需要第三个参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM