我正在研究如何在linux中完成系统调用读/写,我发现了这个:
....
loff_t pos = file_pos_read(f.file);
ret = vfs_read(f.file, buf, count, &pos);
file_pos_write(f.file, pos);
fdput(f);
...`
Run Code Online (Sandbox Code Playgroud)
我的问题是:
锁定在哪里?我想象的是:
....
lock(f.file); // <-- lock file struct
loff_t pos = file_pos_read(f.file);
ret = vfs_read(f.file, buf, count, &pos);
file_pos_write(f.file, pos);
fdput(f);
unlock(f.file); // <-- unlock file struct
...
Run Code Online (Sandbox Code Playgroud)
如果多个线程同时尝试读/写,它们可以在相同的偏移量下读/写?
如果我的理解是正确的,那个linux不使用任何锁定机制来保护偏移量,这个POSIX是否兼容?
我确实看过POSIX规范,但没有发现这个案例.
我想知道为什么dup总是在以下代码中返回零(其中打开一个文件,连续完成10个dup):
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
void main()
{
int i,fdo,fdd;
if((fdo = open("test", O_RDWR | O_CREAT, 0666)) < 0)
{
perror("main open");
return;
}
printf("main open: %d\n",fdo);
for(i=0; i< 10;i++)
{
if((fdd = dup(fdo) < 0 )) {
perror("dup");
return ;
}
printf("opened %d, duped: %d \n", fdo,fdd);
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行程序时(在Linux 2.6.32-279.19.1.el6.i686,Netbsd或Solaris 5.9上),我得到以下结果:
main open: 3
opened 3, duped: 0
opened 3, duped: 0
opened 3, duped: 0
opened 3, duped: 0 …Run Code Online (Sandbox Code Playgroud)