fcntl 文件锁不起作用?
#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;
}
上边的代码试图锁住一个指定的文件以防止别的进程对该文件进行写操作,然而,这个锁似乎并没有起作用。
测试很简单,将上边的代码编译完后起两个进程进行测试,第二个参数不同,就可以发现两个进程同时在写同一个文件了。
奇怪,这段代码哪有问题吗?