I have a simple program going this:
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");
}
Anything wrong with my code? I have made some simple tests and it seems that the problem comes from strcpy
. But according to the definition, I see no problem.
fd
is checked; howlen
andmy_offset
are set; how you check themmap()
call. We can guess that something associated with those caused the code to fail. – LeanoraleantO_CREAT
implies), it will be zero-sized. Accessing a part of ammap()
ed region that doesn't correspond to the underlying file (if any) causes sigbus. Solution:ftruncate()
the file beforemmap()
. – Incorruptible