我有一个程序可以将缓冲区复制到文件中,然后将它们映射回来,然后检查它们的内容。多个线程可以处理同一个文件。有时,我在阅读时会收到 SIGBUS,但只是在负载下。
映射是 MAP_PRIVATE 和 MAP_POPULATE。在 mmap 成功后发生通过 SIGBUS 的崩溃,由于使用了 MAP_POPULATE,我不明白。
这是一个完整的示例(在 /tmp/buf_* 下创建用零填充的文件),使用 OpenMP 创建更多负载和并发写入:
// Program to check for unexpected SIGBUS
// gcc -std=c99 -fopenmp -g -O3 -o mmap_manymany mmap_manymany.c
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#define NBUFS 64
const char bufs[NBUFS][65536] = {{0}};
const char zeros[65536] = {0};
int main()
{
int count = 0;
while ( 1 )
{
void *mappings[ 1000 ] = {NULL};
#pragma omp parallel for
for ( int i = 0; i < 1000; ++i )
{
// Prepare filename
int bufIdx = i % NBUFS;
char path[ 128 ] = { 0 };
sprintf( path, "/tmp/buf_%0d", bufIdx );
// Write full buffer
int outFd = -1;
#pragma omp critical
{
remove( path );
outFd = open( path, O_EXCL | O_CREAT | O_WRONLY | O_TRUNC, 0644 );
}
assert( outFd != -1 );
ssize_t size = write( outFd, bufs[bufIdx], 65536 );
assert( size == 65536 );
close( outFd );
// Map it to memory
int inFd = open( path, O_RDONLY );
if ( inFd == -1 )
continue; // Deleted by other thread. Nevermind
mappings[i] = mmap( NULL, 65536, PROT_READ, MAP_PRIVATE | MAP_POPULATE, inFd, 0 );
assert( mappings[i] != MAP_FAILED );
close( inFd );
// Read data immediately. Creates occasional SIGBUS but only under load.
int v = memcmp( mappings[i], zeros, 65536 );
assert( v == 0 );
}
// Clean up
for ( int i = 0; i < 1000; ++i )
munmap( mappings[ i ], 65536 );
printf( "count: %d\n", ++count );
}
}
我没有断言触发,但程序总是在使用 SIGBUS 几秒钟后崩溃。