一、多个进程以只写模式打开文件
- #include <errno.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/file.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- int main(int argc, char *argv[])
- {
- int fd = open("demo.txt", O_WRONLY, 0644);
- if (fd < 0)
- {
- perror("Open file error");
- exit(EXIT_FAILURE);
- }
- write(fd, "Hello", 5);
- sleep(30);
- return 0;
- }
二、以追加模式打开文件
- #include <sys/stat.h>
- #include <fcntl.h>
- int main(int argc, char *argv[])
- {
- int fd = open("demo.txt", O_WRONLY | O_APPEND, 0644);
- if (fd < 0)
- {
- perror("Open file error");
- exit(EXIT_FAILURE);
- }
- write(fd, "Hello", 5);
- sleep(30);
-
- return 0;
- }
三、为了防止在多进程环境中对同一文件的写操作出现问题,可以对文件加锁,保证这个资源在某一时刻只能被一个进程操作。加锁文件时,如果需要加锁整个文件,可以选用flock,而用fcntl的话,可以对文件的一部分加锁,下面以fcntl函数说明下:
- #include <errno.h>
- #include <fcntl.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #define DEMO_FILE "./demo"
- /* Function to lock or unlock a region of a file */
- int lock_reg(int fd, int cmd, int type, off_t offset, int whence, off_t len)
- {
- struct flock lock;
- lock.l_type = type; /* F_RDLCK, F_WRLCK, F_UNLCK */
- lock.l_start = offset; /* byte offset, relative to l_whence */
- lock.l_whence = whence; /* SEEK_SET, SEEK_CUR, SEEK_END */
- lock.l_len = len; /* #bytes (0 means to EOF) */
- return(fcntl(fd, cmd, &lock));
- }
- int main(int argc, char *argv[])
- {
- int fd = open(DEMO_FILE, O_RDWR);
- if (fd == -1)
- {
- perror("Can not open the specified file");
- exit(EXIT_FAILURE);
- }
- int ret = lock_reg(fd, F_SETLK, F_WRLCK, 0, 0, 0);
- if (ret == -1)
- {
- printf("Error number is: %d\n", errno);
- perror("Can not lock the file");
- exit(EXIT_FAILURE);
- }
- getchar();
- return 0;
- }
很多时候懒得去想问题,特别实在这个大夏天,整个人都会变得很燥,静下来仔细思考遇到过的问题,认真总结,终有云开雾散的时候......