除了用 fork 的方式來實現多線程的方式外,也可以用 clone 的方式.兩者最大的差別是在 Parent copy or not, fork 會copy Parent 的 space, 而 clone 卻是和 Parent 共用 space, 前者比較多用於對外的多平行執行序如external server/client,後者比較多用於 internal的 Process 如 mm management.
fork_smp.c
可發現 Parent 的 data 不會被 Child 改變.
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char *argv[]) {
int count = 1;
int child;
if(!(child = vfork())) {
printf("This is son, his count is: %d. and his pid is: %d\n", ++count, getpid());
} else {
printf("This is father, his count is: %d, his pid is: %d\n", count, getpid());
}
return 0;
}
clone.c
發現 Parent 的 Data 會被 Child 而改變.
#include <stdio.h>
#include <stdlib.h>
#include <sched.h>
#include <signal.h>
#define FIBER_STACK 8192
int a;
void * stack;
int do_something(){
printf("This is son, the pid is:%d, the a is: %d\n", getpid(), ++a);
free(stack);
exit(1);
}
int main() {
void * stack;
a = 1;
stack = malloc(FIBER_STACK);
if(!stack) {
printf("The stack failed\n");
exit(0);
}
printf("creating son thread!!!\n");
clone(&do_something, (char *)stack + FIBER_STACK, CLONE_VM|CLONE_VFORK, 0);
printf("This is father, my pid is: %d, the a is: %d\n", getpid(), a);
exit(1);
}
Refs:
fork,vfork和clone底层实现
fork, vfork, clone,pthread_create,kernel_thread
clone fork及vfork的区别
沒有留言:
張貼留言