- 论坛徽章:
- 2
|
本帖最后由 cdsfiui 于 2017-01-02 10:13 编辑
在代码里面,什么时候需要用clone函数替代fork函数?
clonse()函数的man说到
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()和clone一样可以让父子进程共享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
复制代码 父子进程都能写文件。那么clone创建出来的子进程,在行为上和fork到底有什么不同呢?
|
|