Bus error (flushing kernel) when using strcpy in mmap'ed file

I have a simple program:

int main(void) { int fd; const char *text = "This is a test"; fd = open("/tmp/msyncTest", (O_CREAT | O_TRUNC | O_RDWR), (S_IRWXU | S_IRWXG | S_IRWXO) ); if ( fd < 0 ) { perror("open() error"); return fd; } /* mmap the file. */ void *address; off_t my_offset = 0; address = mmap(NULL, 4096, 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. */ strcpy( (char *)address, text); /* use msync to write changes to disk. */ if ( msync( address, 4096 , MS_SYNC ) < 0 ) { perror("msync failed with error:"); return -1; } else { printf("%s","msync completed successfully."); } close(fd); unlink("/tmp/msyncTest"); } 

Is there something wrong with my code? I did some simple tests and it seems that the problem comes from strcpy . But, by definition, I see no problem.

+5
source share
1 answer

If

 fd = open("/tmp/msyncTest", (O_CREAT | O_TRUNC | O_RDWR), (S_IRWXU | S_IRWXG | S_IRWXO) ); 

successful, fd will refer to a file of zero length ( O_TRUNC ). mmap() call

 address = mmap(NULL, 4096, PROT_WRITE, MAP_SHARED, fd, my_offset); 

sets the memory display, but the pages do not match the object.

http://pubs.opengroup.org/onlinepubs/7908799/xsh/mmap.html has the following message about this situation:

The system always zero fills any partial page at the end of the object. In addition, the system never writes out any changed parts of the last page of an object that is located outside of it. Links within the address range, starting with pa and continuing for len-bytes to entire pages after the end of the object, result in the transmission of a SIGBUS signal.

Similarly, man mmap in Linux notes

Using the displayed area may result in these signals:
[...]
SIGBUS An attempt to access a part of the buffer that does not correspond to the file (for example, outside the file, including the case when another process cut the file).

Therefore, you must ftruncate() save the file with a nonzero length up to mmap() (unless you use mmap() anonymous memory).

+4
source

Source: https://habr.com/ru/post/1234808/


All Articles