|
ace/OS_NS_sys_sendfile.cpp中sendfile_emulation的实现有些问题,unix系统ACE_OS::mmap的offset参数必须是内存页面大小的整数倍,否则会出错。虽然常用的是0,但有时用到非0值的时候就要注意了。
简单修改了下。(假设内存页大小为4k)
在windows上可以用TransmitFile()来模拟。具体实现相当tricky,详细说明见代码注释。
- // $Id: OS_NS_sys_sendfile.cpp 84216 2009-01-22 18:34:40Z johnnyw $
- #include "ace/OS_NS_sys_sendfile.h"
- #include "ace/OS_NS_sys_mman.h"
- #include "ace/OS_NS_unistd.h"
- #if defined (ACE_WIN32) || defined (HPUX)
- # include "ace/OS_NS_sys_socket.h"
- #else
- # include "ace/OS_NS_unistd.h"
- #endif /* ACE_WIN32 || HPUX */
- #ifndef ACE_HAS_INLINED_OSCALLS
- # include "ace/OS_NS_sys_sendfile.inl"
- #endif /* ACE_HAS_INLINED_OSCALLS */
- ACE_BEGIN_VERSIONED_NAMESPACE_DECL
- #if defined ACE_HAS_SENDFILE && ACE_HAS_SENDFILE == 0
- ssize_t
- ACE_OS::sendfile_emulation (ACE_HANDLE out_fd,
- ACE_HANDLE in_fd,
- off_t * offset,
- size_t count)
- {
- // @@ Is it possible to inline a call to ::TransmitFile() on
- // MS Windows instead of emulating here?
- // @@ We may want set up a signal lease (or oplock) if supported by
- // the platform so that we don't get a bus error if the mmap()ed
- // file is truncated.
- #if defined (ACE_WIN32)
- // 0表示取系统默认值,也可自定义大小
- static const size_t BytesPerSend = 0;
- if (offset != NULL)
- ACE_OS::lseek(in_fd, (ACE_OFF_T)offset, SEEK_SET);
- // 记录发送前文件指针位置
- ACE_OFF_T currentOffset = ACE_OS::lseek(in_fd, 0, SEEK_CUR);
- // 当前文件指针+count不得超过文件尾,否则TransmitFile出错WSAEINVAL。
- // 此时需修改count
- ACE_OFF_T eofPosition = ACE_OS::lseek(in_fd, 0, SEEK_END);
- ACE_OS::lseek(in_fd, currentOffset, SEEK_SET);
- size_t bytesLeft = (size_t)(eofPosition - currentOffset);
- if (bytesLeft < count)
- count = bytesLeft;
- // 发送从当前文件指针开始的count个字节的数据
- // count==0表示传送从当前文件指针到文件尾的所有数据
- BOOL suc = ::TransmitFile((SOCKET)out_fd, in_fd, count, BytesPerSend, 0, 0, TF_USE_DEFAULT_WORKER);
- if (suc == FALSE)
- return -1;
- // TransmitFile()的文件指针自动设置不可依赖(仅在第一次调用时前进BytesPerSend,
- // 而不是实际发送值count,而且以后再次调用时不再前进)。需要自己控制绝对值
- currentOffset += count;
- ACE_OS::lseek(in_fd, currentOffset, SEEK_SET);
- return count;
- #endif
- const size_t alignmentGranularity = 4 * 1024; // page size on unix
- off_t adjustedOffset = (*offset / (alignmentGranularity)) * alignmentGranularity;
- void * const buf =
- ACE_OS::mmap (0, count, PROT_READ, MAP_SHARED, in_fd, adjustedOffset);
- if (buf == MAP_FAILED)
- return -1;
- size_t memoryOffset = *offset % (alignmentGranularity);
- void* readPtr = (char*)buf + memoryOffset;
- size_t countLeft = count - memoryOffset;
- #if defined (HPUX)
- ssize_t const r =
- ACE_OS::send (out_fd, static_cast<const char *> (readPtr), countLeft);
- #else
- ssize_t const r = ACE_OS::write (out_fd, readPtr, countLeft);
- #endif /* HPUX */
- (void) ACE_OS::munmap (buf, count);
- if (r > 0)
- *offset += static_cast<off_t> (r);
- return r;
- }
- #endif /* ACE_HAS_SENDFILE==0 */
- ACE_END_VERSIONED_NAMESPACE_DECL
复制代码
[ 本帖最后由 wishel 于 2009-11-10 14:53 编辑 ] |
|