linux 创建锁文件

来源:互联网 发布:linux自启动shell脚本 编辑:程序博客网 时间:2024/05/21 22:57

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>

int main()
{
int file_desc;
int save_errno;
file_desc = open("/tmp/LCK.test",O_RDWR|O_CREAT|O_EXCL,0444);
if(file_desc == -1)
{
save_errno = errno;
printf("open failed with error %d\n",save_errno);
}
else
{
printf("open succeeded\n");
}

exit(EXIT_SUCCESS);
}
说明:

1. 0444(零)  代表owner、group、others都有读权限。

2. Ensure that this call creates the file: if this flag is spec‐
              ified  in  conjunction  with  O_CREAT,  and  pathname already
              exists, then open() will fail.
In general, the behavior of O_EXCL is undefined if it is used
              without  O_CREAT.

3.save_errno = errno;
printf("open failed with error %d\n",save_errno);
save_errno是防止printf的调用影响errno的值。