- 论坛徽章:
- 0
|
每个进程都有自己的文件表项,因此每个进程都有自己对文件的偏移量。lseek和write不是一个原子操作。因此b进程可能替换了a进程写入的内容。要达到楼主想要的效果有两种方式:
1.不加记录锁,打开文件的时候用O_APPEND状态标记,这样内核在写的时候会把当前位移量移动到文件的末尾处。
if ((fd = open(fn, O_WRONLY | O_CREAT|O_APPEND, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0) {
perror("open:");
exit(-1);
}
2.把记录锁加到循环外面- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <string.h>
- #define CNT 100
- void write_file(int fd, char data, size_t len);
- int main(int argc, char *argv[])
- {
- char fn[]="flock-demo";
- int fd;
- pid_t pid;
- if (argc > 1)
- strcpy(fn,argv[1]);
- if ((fd = open(fn, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0) {
- perror("open:");
- exit(-1);
- }
- for (int i = 0; i < CNT; i++) {
- if ((pid = fork()) < 0) {
- perror("fork:");
- exit(-1);
- } else {
- if (pid == 0) {
- /* child process */
- write_file(fd, i, sizeof(i));
- exit(0);
- }
- }
- }
- return 0;
- }
- void write_file(int fd, char data, size_t len)
- {
- struct flock fl;
- fl.l_whence = SEEK_SET;
- fl.l_start = 0;
- fl.l_len = 0;
- fl.l_type = F_WRLCK;
- if (fcntl(fd, F_SETLKW, &fl) < 0) {
- perror("fcntl:");
- exit(-1);
- }*
- for (int i = 0; i < CNT; i++) {
-
- ssize_t wlen = write(fd, &data, len);
- if (wlen < 0) {
- perror("write:");
- exit(-1);
- }
- else {
- if ((size_t)wlen < len) {
- fprintf(stderr, "Other write error in process %d\n", getpid());
- exit(-1);
- }
- }
-
- }
- fl.l_type = F_UNLCK;
- if (fcntl(fd, F_SETLKW, &fl) < 0) {
- perror("fcntl:");
- exit(-1);
- }
- }
复制代码 |
|