fcntl 文件锁不起作用?

LuoTing 2004-04-21 03:47:43
#include <fstream.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <iostream>

using namespace std;

int main(int argc, char** argv)
{
if (argc<3) return 1;
cout << argv[1] << endl;
char* dirName = argv[1];
#include <iostream>

using namespace std;

int main(int argc, char** argv)
{
if (argc<3) return 1;
cout << argv[1] << endl;
char* dirName = argv[1];

char* cont = argv[2];
struct flock flk;
flk.l_type = F_WRLCK; /* F_RDLCK, F_WRLCK, F_UNLCK */
flk.l_start = 0;
flk.l_whence = SEEK_SET;
flk.l_len = 0; /* length, 0 = to EOF */
flk.l_pid = getpid();

int fd = open(dirName,O_WRONLY);
cout << flk.l_pid << " opening the file:" << fd << endl;

int rt = fcntl(fd, F_SETLK, &flk); // get a write lock
cout << "locked the file as write:" << rt << endl;

int size = 2;
for (int i = 0; i < 60; i++)
{
write(fd, cont, strlen(cont));
sleep(1);
cout << (60-i);
}
cout << endl;
close(fd);
cout << "close file and exit." << endl;
return 0;
}

上边的代码试图锁住一个指定的文件以防止别的进程对该文件进行写操作,然而,这个锁似乎并没有起作用。
测试很简单,将上边的代码编译完后起两个进程进行测试,第二个参数不同,就可以发现两个进程同时在写同一个文件了。

奇怪,这段代码哪有问题吗?
...全文
103 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
LuoTing 2004-04-21
  • 打赏
  • 举报
回复
明白了,这只是建议性锁。
LuoTing 2004-04-21
  • 打赏
  • 举报
回复
哦,编辑有点问题,代码应该如下:
#include <fstream.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <iostream>

using namespace std;

int main(int argc, char** argv)
{
if (argc<3) return 1;
cout << argv[1] << endl;
char* dirName = argv[1];

char* cont = argv[2];
struct flock flk;
flk.l_type = F_WRLCK; /* F_RDLCK, F_WRLCK, F_UNLCK */
flk.l_start = 0;
flk.l_whence = SEEK_SET;
flk.l_len = 0; /* length, 0 = to EOF */
flk.l_pid = getpid();

int fd = open(dirName,O_WRONLY);
cout << flk.l_pid << " opening the file:" << fd << endl;

int rt = fcntl(fd, F_SETLK, &flk); // get a write lock
cout << "locked the file as write:" << rt << endl;

int size = 2;
for (int i = 0; i < 60; i++)
{
write(fd, cont, strlen(cont));
sleep(1);
}

close(fd);
cout << "close file and exit." << endl;
return 0;
}

69,373

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧