我想知道如何在fork()中发生copy-on-write.
假设我们有一个具有动态int数组的进程A:
int *array = malloc(1000000*sizeof(int));
Run Code Online (Sandbox Code Playgroud)
数组中的元素初始化为一些有意义的值.然后,我们使用fork()创建一个子进程,即B.B将迭代数组并进行一些计算:
for(a in array){
a = a+1;
}
Run Code Online (Sandbox Code Playgroud)
a = a+1?a = a+1;这是怎么发生的?B是否从A读取数据并将新数据写入其自己的数组?我写了一些代码来探索COW如何工作.我的环境:ubuntu 14.04,gcc4.8.2
#include <stdlib.h>
#include <stdio.h>
#include <sys/sysinfo.h>
void printMemStat(){
struct sysinfo si;
sysinfo(&si);
printf("===\n");
printf("Total: %llu\n", si.totalram);
printf("Free: %llu\n", si.freeram);
}
int main(){
long len = 200000000;
long *array = malloc(len*sizeof(long));
long i = 0;
for(; i<len; i++){
array[i] = i;
}
printMemStat();
if(fork()==0){
/*child*/
printMemStat();
i = 0;
for(; i<len/2; i++){
array[i] = i+1; …Run Code Online (Sandbox Code Playgroud) 我最近在读Redis.Redis实现了一个基于I/O多路复用的简单事件驱动库.Redis表示会选择系统支持的最佳多路复用,并提供以下代码:
/* Include the best multiplexing layer supported by this system.
* The following should be ordered by performances, descending. */
#ifdef HAVE_EVPORT
#include "ae_evport.c"
#else
#ifdef HAVE_EPOLL
#include "ae_epoll.c"
#else
#ifdef HAVE_KQUEUE
#include "ae_kqueue.c"
#else
#include "ae_select.c"
#endif
#endif
#endif
Run Code Online (Sandbox Code Playgroud)
我想知道他们是否有基本的性能差异?如果是这样,为什么?
最好的祝福
如果我知道数据对象的地址,我可以将地址存储为整数并将整数作为指针操作吗?
例如,
void main(){
long a = 101010;
long *p = &a;
long b = p;
printf("%lld\n", *(long*)b);
}
Run Code Online (Sandbox Code Playgroud)
总是安全吗?
评论:long b = p;产生警告:
Initialization makes integer from pointer without a cast
Run Code Online (Sandbox Code Playgroud)
但是,该程序打印101010.