【发布时间】:2016-01-07 04:47:26
【问题描述】:
文件'hello'的内容是hello。
$ od -tx1 -tc hello
0000000 68 65 6c 6c 6f 0a
h e l l o \n
0000006
下面是我对文件“hello”进行一些更改的代码。
static void *task();
int main(void)
{
int *p;
pthread_t Thread;
int fd = open("hello", O_RDWR);
if (fd < 0) {
perror("open hello");
exit(1);
}
p = mmap(NULL, 6, PROT_WRITE, MAP_PRIVATE, fd, 0);
if (p == MAP_FAILED) {
perror("mmap");
exit(1);
}
close(fd);
pthread_create(&Thread, NULL, &task, p)
printf("Help");
pthread_join(Thread, 0);
munmap(p, 6);
return 0;
}
static void * task(int *r)
{
r[0] = 0x30313233;
}
上面的代码我用了MAP_PRIVATE,好像子线程不行。
如果我将 MAP_PRIVATE 更改为 MAP_SHARED,我会发现它会产生预期的不同。
$ od -tx1 -tc hello
0000000 33 32 31 30 6f 0a
3 2 1 0 o \n
0000006
但我不知道它是怎么发生的。
【问题讨论】:
-
man mmap: MAP_PRIVATE Create a private copy-on-write mapping. Updates to the mapping [...] are not carried through to the underlying file.。此外,您还违反了严格的别名。 -
@EOF 感谢您的回复。我已经意识到我的问题...