miwaiwai

导航

flock()文件锁使用例子

void *pth_fun(void *pth_arg)
{
int fd;

fd = open("./hello", O_RDWR|O_CREAT|O_TRUNC, 0664);
if (fd == -1) print_err("./hello", __LINE__, errno);
while(1)
{
flock(fd, LOCK_EX);
write(fd, "hello ", 6);
write(fd, "world\n", 6);
flock(fd, LOCK_UN);
}
return NULL;
}

int main(int argc, char *argv[])
{
int fd = -1;
int ret = -1;
pthread_t tid;

fd = open("./hello", O_RDWR|O_CREAT|O_TRUNC, 0664);
if (fd == -1) print_err("./hello", __LINE__, errno);

ret = pthread_create(&tid, NULL, pth_fun, NULL);
if (ret == -1) print_err("pthread_create fail", __LINE__, ret);

while(1)
{
flock(fd, LOCK_EX);
write(fd, "hello ", 6);
write(fd, "world\n", 6);
flock(fd, LOCK_UN);
}

return 0;
}

 

posted on 2023-02-26 17:37  米歪歪  阅读(37)  评论(0编辑  收藏  举报