简体   繁体   English

linux c:什么时候需要“ clone”功能而不是“ fork”?

[英]linux c: When do I need “clone” function instead of “fork”?

The man page says: 手册页显示:

Unlike fork(2), clone() allows the child process to share parts of its execution context with the calling process, such as the memory space, the table of file descriptors, and the table of signal handlers. 与fork(2)不同,clone()允许子进程与调用进程共享其执行上下文的各个部分,例如内存空间,文件描述符表和信号处理程序表。 (Note that on this manual page, "calling process" normally corresponds to "parent process". But see the description of CLONE_PARENT below.) (请注意,在此手册页上,“调用过程”通常对应于“父过程”。但是请参见下面的CLONE_PARENT的描述。)

What I don't understand is "the table of file descriptors", because when I use fork, the child can of course write to the FD that's opened by father process, like I tested below: 我不理解的是“文件描述符表”,因为当我使用fork时,孩子当然可以写入由父进程打开的FD,就像我在下面测试的那样:

$ cat myfork.cpp
#include<fcntl.h>
#include<unistd.h>
int main()
{
    int f1=open("./test.txt",O_CREAT|O_RDWR);
    pid_t id=fork();
    if(id>0)//father
    {
    sleep(1);
    for(size_t i=0;i<10;++i)
    {
        sleep(2);
        write(f1,"father write1\n",14);
    }
    }
    else//child
    {
    for(size_t i=0;i<10;++i)
    {
        sleep(2);
        write(f1,"child write1\n",13);
    }
    }
    close(f1);
    return 0;
}

The running result is: 运行结果为:

$ cat test.txt
child write1
father write1
child write1
father write1
child write1
father write1
child write1
father write1
child write1
father write1
child write1
father write1
child write1
father write1
child write1
father write1
child write1
father write1
child write1
father write1

Both process can write to same file in turn, so can I understand that "forked" process can also share fd table? 这两个进程可以依次写入同一文件,所以我可以理解“分叉”进程也可以共享fd表吗? Then what's the necessity of "clone" function? 那么“克隆”功能的必要性是什么?

The table is not shared, it's copied. 该表未共享,已被复制。 After a fork , each process has its own file descriptor table. fork ,每个进程都有自己的文件描述符表。

To implement things like threads, you need the table to be shared such that changes to the file descriptor are seen in both scheduling entities. 要实现诸如线程之类的功能,您需要共享表,以便在两个调度实体中都能看到对文件描述符的更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM