我在网上看到过这个问题,不确定我的答案是否正确:
#include <unistd.h>
#include <sys/wait.h>
#define N 100*1024*1024
int a[N];
int main() {
if (fork() > 0) {
wait(nullptr);
} else {
for (unsigned int i = 0; i < N; ++i) {
a[i] = 1;
}
}
return 0;
}
问题是:
考虑到在x86-64操作系统中启用了COW技术(页面大小为4KB=4096B(,子进程在整个运行时会创建多少页面错误。(不寻找非常准确的答案(
- 1024*1
- 1024*10
- 1024*100
- 1024*1024
- 1024*1024*10
- 1024*1024*100
我认为正确的是6,因为每当子进程尝试写入内存中受写保护的位置时,我们都会尝试复制N
元素。我说得对吗?
我试着用我的程序运行strace
,但似乎没有一个是正确的,因为输出中没有包含代表每个页面错误的数千行:
strace ./a.out
execve("./a.out", ["./a.out"], 0x7ffd84f9ace0 /* 50 vars */) = 0
brk(NULL) = 0x55c515202000
access("/etc/ld.so.nohwcap", F_OK) = -1 ENOENT (No such file or directory)
access("/etc/ld.so.preload", R_OK) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
fstat(3, {st_mode=S_IFREG|0644, st_size=96020, ...}) = 0
mmap(NULL, 96020, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f93cbf68000
close(3) = 0
access("/etc/ld.so.nohwcap", F_OK) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
read(3, "177ELF2113 3 >