I have seen this question online, and am not sure if my answer is correct or not:
#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;
}
The question was:
Considering COW technique is enabled in x86-64 OS (With a page size of 4KB = 4096B) how many page faults the child process creates during its whole runtime. (Not looking for very exact answer)
- 1024*1
- 1024*10
- 1024*100
- 1024*1024
- 1024*1024*10
- 1024*1024*100
I think the correct one is 6 since we will try to copy N elements each time the child process tries to write to a write-protected location in memory. Am I right?
I tried to run strace with my program, and it seems none are correct, as the output didn't contain any thousands of lines representing each page fault:
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, "\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\20\35\2\0\0\0\0\0"..., 832) = 832
fstat(3, {st_mode=S_IFREG|0755, st_size=2030928, ...}) = 0
mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f93cbf66000
mmap(NULL, 4131552, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f93cb966000
mprotect(0x7f93cbb4d000, 2097152, PROT_NONE) = 0
mmap(0x7f93cbd4d000, 24576, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1e7000) = 0x7f93cbd4d000
mmap(0x7f93cbd53000, 15072, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7f93cbd53000
close(3) = 0
arch_prctl(ARCH_SET_FS, 0x7f93cbf674c0) = 0
mprotect(0x7f93cbd4d000, 16384, PROT_READ) = 0
mprotect(0x55c4fb12b000, 4096, PROT_READ) = 0
mprotect(0x7f93cbf80000, 4096, PROT_READ) = 0
munmap(0x7f93cbf68000, 96020) = 0
clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7f93cbf67790) = 3341
wait4(-1, NULL, 0, NULL) = 3341
--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=3341, si_uid=1000, si_status=0, si_utime=19, si_stime=35} ---
exit_group(0) = ?
+++ exited with 0 +++