- 论坛徽章:
- 84
|
30可用积分
一个客户给的测试程序,总是 Bus error,求解决:
RHEL-6.7
gdb 发现出错的地方就是一个 mmap 后的地址赋值,why ?
代码:- #define _GNU_SOURCE /* See feature_test_macros(7) */
- #include <sched.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <sys/mman.h>
- #include <unistd.h>
- #define TPATH "testfile"
- #define SIZE (20*4096)
- #define NPAGES 4
- int main(int argc, char *argv[]) {
- int filp_foo, pos, *p;
- char buf[32];
- char *foo_addr;
- cpu_set_t *cpusetp = CPU_ALLOC(4);
- CPU_SET(0, cpusetp);
- sched_setaffinity(0, sizeof(cpu_set_t), cpusetp);
- unlink(TPATH);
- filp_foo = open(TPATH, O_RDWR|O_CREAT|O_SYNC, S_IWUSR|S_IRUSR|S_IRGRP|S_IROTH);
- ftruncate(filp_foo, SIZE);
- foo_addr = mmap(NULL, SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, filp_foo, 0);
- p = (int *)foo_addr;
- *p = SIZE;
- if (!fork()) {
- CPU_SET(1, cpusetp);
- sched_setaffinity(0, sizeof(cpu_set_t), cpusetp);
- for (pos = SIZE; pos >= 0; pos -= 4096) {
- *p = pos;
- ftruncate(filp_foo, pos);
- }
- return 0;
- } else {
- int tpos = (16*4096);
- restart:
- // spin-wait for the other thread to truncate:
- while (tpos == *p) {}
- if (*p < 1) {
- *p = (16*4096);
- }
- tpos = *p;
- usleep(100);
- for (pos = tpos - 4096*NPAGES; pos <= tpos && pos > 0; pos += 4096) {
- foo_addr[pos] = 'b';
- }
- // trigger readpage:
- pread(filp_foo, buf, 32, tpos);
- if (*p >= 4096)
- goto restart;
- }
- return 0;
- }
复制代码 |
最佳答案
查看完整内容
你在子进程里把文件截短了,父进程访问被截掉的地方当然会sigbus。
|