简体   繁体   中英

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. (Note that on this manual page, "calling process" normally corresponds to "parent process". But see the description of CLONE_PARENT below.)

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:

$ 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? 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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