商业网站的规划和设计linux wordpress 升级
news/
2025/10/3 21:01:59/
文章来源:
商业网站的规划和设计,linux wordpress 升级,微信公众号免费做影视网站,俄罗斯国家馆电商平台在C语言中#xff0c;flock 是一个用于文件锁定的函数#xff0c;定义在 sys/file.h 头文件中。它的主要目的是在对文件进行读写操作时#xff0c;避免其他进程同时访问文件#xff0c;以实现文件的并发控制。
flock 函数的原型
#include sys/file.hint flock(in…在C语言中flock 是一个用于文件锁定的函数定义在 sys/file.h 头文件中。它的主要目的是在对文件进行读写操作时避免其他进程同时访问文件以实现文件的并发控制。
flock 函数的原型
#include sys/file.hint flock(int fd, int operation);参数
fd: 文件描述符通常通过 open 函数获得。operation: 锁定操作的类型通常是以下几种之一 LOCK_SH: 共享锁允许其他进程读取文件但不允许写入。LOCK_EX: 排他锁阻止其他进程读取或写入文件。LOCK_UN: 解锁释放之前的锁。LOCK_NB: 非阻塞模式锁定操作不会被阻塞如果锁定失败flock 立即返回错误。
返回值
成功返回 0。失败返回 -1并设置 errno 以指示错误原因。
示例
进程A1写入完成前进程A2的写入被阻塞进程A3的读取被阻塞。
A1.c
#include fcntl.h
#include stdio.h
#include stdlib.h
#include string.h
#include sys/file.h
#include unistd.h
int main() {int fd open(example.txt, O_WRONLY | O_CREAT | O_TRUNC, 0666);if (fd 0) {perror(open);exit(EXIT_FAILURE);}// 加锁if (flock(fd, LOCK_EX) 0) {perror(flock);close(fd);exit(EXIT_FAILURE);}printf(File is locked. Performing operations...\n);const char *message Hello, World!\n; // 要写入的数据// 写入数据ssize_t bytesWritten write(fd, message, strlen(message));if (bytesWritten 0) {perror(write);close(fd);exit(EXIT_FAILURE);} else {printf(Successfully wrote %ld bytes to the file.\n, bytesWritten);}sleep(10);// 简化写入过程不做成功判断 仅测试用const char *endmsg The End!\n;write(fd, endmsg, strlen(endmsg));printf(writing finished\n);// 解锁if (flock(fd, LOCK_UN) 0) {perror(flock);close(fd);exit(EXIT_FAILURE);}close(fd);return 0;
}
A2.c
#include fcntl.h
#include stdio.h
#include stdlib.h
#include string.h
#include sys/file.h
#include unistd.h
int main() {int fd open(example.txt, O_WRONLY | O_CREAT | O_TRUNC, 0666);if (fd 0) {perror(open);exit(EXIT_FAILURE);}// 加锁if (flock(fd, LOCK_EX) 0) {perror(flock);close(fd);exit(EXIT_FAILURE);}// 简化写入过程不做成功判断 仅测试用const char *newmsg new msg!\n;write(fd, newmsg, strlen(newmsg));// 解锁if (flock(fd, LOCK_UN) 0) {perror(flock);close(fd);exit(EXIT_FAILURE);}close(fd);return 0;
}
A3.c
#include stdio.h
#include stdlib.h
#include fcntl.h
#include sys/file.h
#include unistd.h#define BUFFER_SIZE 256int main() {// 打开文件以只读模式int fd open(example.txt, O_RDONLY);if (fd 0) {perror(open);exit(EXIT_FAILURE);}// 获取共享锁if (flock(fd, LOCK_SH) 0) {perror(flock);close(fd);exit(EXIT_FAILURE);}// 读取数据char buffer[BUFFER_SIZE];ssize_t bytesRead read(fd, buffer, sizeof(buffer) - 1);if (bytesRead 0) {perror(read);flock(fd, LOCK_UN); // 解锁close(fd);exit(EXIT_FAILURE);}// 读取到的数据添加终止符buffer[bytesRead] \0;// 输出读取的数据printf(Read from file: %s\n, buffer);// 解锁if (flock(fd, LOCK_UN) 0) {perror(flock);close(fd);exit(EXIT_FAILURE);}// 关闭文件close(fd);return 0;
}
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/926311.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!