日期:2014-05-16  浏览次数:20599 次

【疑问求助】lseek函数和pwrite函数《APUE》
pwrite是atomic operation的产物
操作1.对于单进程操作来先调用lseek 然后调用write
操作2.直接调用pwrite
APUE上说是等价的,只要操作1在调用lseek和write之间,不被打断,1,2就是等价的
原话:
Calling pread is  equivalent  to  calling lseek followed  by  a  call  to read,with  the
following exceptions.
 ?There is no way to interrupt the two operations that occur when we call pread.
 ?The current file offset is not updated. 

Calling pwrite is equivalent to calling lseek followed by a call to write,with similar
exceptions.

In general, the term atomic operation refers to an operation that might be composed
of  multiple  steps. If  the  operation  is  performed  atomically ,either  all  the  steps  are performed (on success) or none are performed (on failure).  

APUE没有给出示例代码
我自己练习时候发现了问题
ssize_t pwrite(int fd ,const void *buf,size_tnbytes ,off_t offset);
这个是pwrite的原型
观察,最后一个参数,offset,这个变量怎么得到呢?除了lseek返回offset还能怎样
但是pwrite从逻辑上讲又是lseek+write
这个时候是没有offset参数来源的,必须在pwrite之前调用一个lseek得到当前offset,以此来作为pwrite的参数
但是问题来了,如果这样调用的话,那么pwrite就显得很没意义,因为都是lseek+write或则lseek+pwrite
pwrite反而显得多此一举了

渣渣愚昧,恳请大神明示
------解决方案--------------------
$man pwrite
........
pwrite() writes up to count bytes from the buffer starting at buf to the file descriptor fd at offset offset.  
The file offset is not changed.
............