gpt4 book ai didi

c - Linux C : When do I need "clone" function instead of "fork"?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:34:14 26 4
gpt4 key购买 nike

手册页说:

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.)

我不明白的是“文件描述符表”,因为当我使用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;
}

运行结果为:

$ 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

两个进程可以轮流写入同一个文件,所以我可以理解“forked”进程也可以共享fd表吗?那么“克隆”功能的必要性是什么?

最佳答案

该表不是共享的,而是复制的。在 fork 之后,每个进程都有自己的文件描述符表。

要实现线程之类的东西,您需要共享表,以便在两个调度实体中都能看到文件描述符的更改。

关于c - Linux C : When do I need "clone" function instead of "fork"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41420689/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com