See how the COW finish the copy

About

The COW is Copy on Write,In my reading the Redis Database’s code process,i have had a problem:How redis to finish write in file when have other thread using the file?

Learning

Linux have some C function which namedfork() and exec(),for example,i will write some code to show how these function work.

1
2
3
4
5
6
7
8
9
// main.c
#include <stdio.h>
#include <unistd.h>

void main(void){
int time = 1;
pid_t pid = fork();
printf("%d",time);
}

now we use gcc to build the out file and run it.

1
2
3
4
5
6
7
8
root@minloha:~/LearnCcode/fork# ls
main.c
root@minloha:~/LearnCcode/fork# gcc -g -o testmodel main.c
root@minloha:~/LearnCcode/fork# ls
main.c testmodel
root@minloha:~/LearnCcode/fork# ./testmodel
11
root@minloha:~/LearnCcode/fork#

we can see the shell have double 1,we use gdb testing it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
root@minloha:~/LearnCcode/fork# gdb testmodel
(gdb) start
Temporary breakpoint 1 at 0x1169: file main.c, line 4.
Starting program: /root/LearnCcode/fork/testmodel

Temporary breakpoint 1, main () at main.c:4
4 void main(void){
(gdb) n
5 int time = 1;
(gdb) n
6 pid_t pid = fork();
(gdb) n
[Detaching after fork from child process 291435]
7 printf("%d",time);
(gdb) 1n
8 }
(gdb) n
__libc_start_main (main=0x555555555169 <main>, argc=1, argv=0x7fffffffe568, init=<optimized out>,
fini=<optimized out>, rtld_fini=<optimized out>, stack_end=0x7fffffffe558) at ../csu/libc-start.c:342
342 ../csu/libc-start.c: No such file or directory.
(gdb)

in line six , GDB tell us the child process have been detach,we copied the parent process to the child process. After the content is output, the child process automatically disengages,untill finish the testing and remove the main process from the stack.

In this process, although our program have runing,the new process also be created, this is COW(copy on write),the child process(renamed B) copy the parent process(renamed A),if the system at this time still contains space, allocate a part to B so that B has enough resources to create child processes. if the space is insufficient, continue to use the resources of the parent process.

Is Redis,we need to make data persistent,But we couldn’t close the server, so we should use snapshotting , which is copy on write

Expend

except Copy on write,also have read on write(ROW)there are many similarities between the two. COW and ROW all used into snapshot technology


See how the COW finish the copy
https://blog.minloha.cn/posts/142247e313251a2022062240.html
作者
Minloha
发布于
2022年6月22日
更新于
2024年4月8日
许可协议