我正在尝试使用clone()系统调用来创建一个与父进程共享资源的线程.
在本书中,我读到如果我使用以下标志,我将能够这样做:
CLONE_VM | CLONE_FILES | CLONE_SIGHAND | CLONE_FS
但似乎变量没有被分享.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <linux/sched.h>
#include <string.h>
#define STACK_SIZE 65536
#define BUFSIZE 200
int n = 5;
int Child(void *);
int main() {
pid_t pid;
char *stack;
stack = malloc(STACK_SIZE);
pid = clone(Child,stack + STACK_SIZE, CLONE_SIGHAND|CLONE_FS|CLONE_VM|CLONE_FILES);
wait(NULL);
char buf[BUFSIZE];
sprintf(buf,"Back to parent: Value of n: %d\n",n);
write(1,buf,strlen(buf));
return 0;
}
int Child(void *args) {
n += 15;
char buf[BUFSIZE];
sprintf(buf,"In child: Value of n: %d\n",n);
write(1,buf,strlen(buf));
}
输出也在不断变化.我糊涂了.
最佳答案
int n = 5;
int Child(void *);
int main() {
int n = 5;
你有两个名为n的变量. Child在全局上运行,但main使用其范围中定义的那个.
您还应该将等待调用更改为waitpid(-1,NULL,__ WAL),否则您实际上不会等待克隆进程. (或者您可以将| SIGCHLD添加到克隆选项中.)
来自clone(2)
文档:
The low byte of flags contains the number of the termination signal sent to
the parent when the child dies. If this signal is specified as anything other
than SIGCHLD, then the parent process must specify the __WALL or __WCLONE
options when waiting for the child with wait(2). If no signal is specified,
then the parent process is not signaled when the child terminates.