加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

克隆()系统调用C和共享

发布时间:2020-12-16 07:32:19 所属栏目:百科 来源:网络整理
导读:我正在尝试使用clone()系统调用来创建一个与父进程共享资源的线程. 在本书中,我读到如果我使用以下标志,我将能够这样做: CLONE_VM | CLONE_FILES | CLONE_SIGHAND | CLONE_FS 但似乎变量没有被分享. #include stdio.h#include stdlib.h#include sys/types.h
我正在尝试使用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: %dn",n);
    write(1,buf,strlen(buf));
    return 0;
}
int Child(void *args) {
    n += 15;
    char buf[BUFSIZE];
    sprintf(buf,"In child: Value of n: %dn",n); 
    write(1,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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读