Linux使用clone()做异步
我试图用克隆来计算一个数字,但我发现我是这样使用的。我会让它只工作在第一个孩子,然后得到分割错误。我怎样才能异步执行add_计数器 下面是我的代码:Linux使用clone()做异步,linux,clone,Linux,Clone,我试图用克隆来计算一个数字,但我发现我是这样使用的。我会让它只工作在第一个孩子,然后得到分割错误。我怎样才能异步执行add_计数器 下面是我的代码: #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <sched.h> #define STACK 8192 int counter; void * stack; int add_counter(){ while(1)
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <sched.h>
#define STACK 8192
int counter;
void * stack;
int add_counter(){
while(1) {
printf("This is son, the pid is:%d, the a is: %d\n", getpid(), ++counter);
free(stack);
if (counter == 1000)
exit(1);
}
}
int main() {
void * stack;
counter = 0;
stack = malloc(STACK);
if(!stack) {
printf("The stack failed\n");
exit(0);
}
int i;
for (i = 0; i < 10; i++) {
clone(&add_counter, (char *)stack + STACK, CLONE_VM|CLONE_VFORK, 0);
}
printf("This is father, my pid is: %d, the a is: %d\n", getpid(), counter);
// exit(1);
}
提前谢谢
......
This is son, the pid is:3865, the a is: 985
This is son, the pid is:3865, the a is: 986
This is son, the pid is:3865, the a is: 987
This is son, the pid is:3865, the a is: 988
This is son, the pid is:3865, the a is: 989
This is son, the pid is:3865, the a is: 990
This is son, the pid is:3865, the a is: 991
This is son, the pid is:3865, the a is: 992
This is son, the pid is:3865, the a is: 993
This is son, the pid is:3865, the a is: 994
This is son, the pid is:3865, the a is: 995
This is son, the pid is:3865, the a is: 996
This is son, the pid is:3865, the a is: 997
This is son, the pid is:3865, the a is: 998
This is son, the pid is:3865, the a is: 999
This is son, the pid is:3865, the a is: 1000
Segmentation fault