我刚刚学习了msync的使用,但我遇到了问题segmentation fault
。当我将MAPSTEP
更改为较小的数字时,错误就消失了。这段代码有什么问题?
#define MAPSTEP 1 * 4096
main(void) {
size_t bytesWritten =0;
int fd;
const char text[MAPSTEP];
memset(text, '-', sizeof(char) * MAPSTEP);
fd = open("/tmp/mmsyncTest", (O_CREAT | O_TRUNC | O_RDWR),
(S_IRWXU | S_IRWXG | S_IRWXO));
if ( fd < 0 ) {
perror("open() error");
return fd;
}
off_t lastoffset = lseek( fd, MAPSTEP, SEEK_SET);
bytesWritten = write(fd, " ", 1 );
if (bytesWritten != 1 ) {
perror("write error. ");
return -1;
}
/* mmap the file. */
void *address;
int len;
off_t my_offset = 0;
len = MAPSTEP; /* Map page */
address = mmap(NULL, len, PROT_WRITE, MAP_SHARED, fd, my_offset);
if ( address == MAP_FAILED ) {
perror("mmap error. " );
return -1;
}
/* Move some data into the file using memory map. */
(void) strcpy( (char*) address, text);
/* use msync to write changes to disk. */
if ( msync( address, MAPSTEP , MS_SYNC ) < 0 ) {
perror("msync failed with error:");
return -1;
}
else (void) printf("%s","msync completed successfully.\n");
close(fd);
unlink("/tmp/msyncTest");
}
答案 0 :(得分:0)
函数unlink中的一个观察结果(“/ tmp / msyncTest”);是,文件名与您之前打开的文件名不同。它也可能会产生分段错误。