cdsfiui 发表于 2017-01-02 10:12

fork()和clone()创建的进程都可以共享FD,这两个函数到底有何不同?

本帖最后由 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 asthememoryspace,
       thetableoffiledescriptors, 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到底有什么不同呢?

MMMIX 发表于 2017-01-02 13:42

回复 1# cdsfiui

在代码里面,什么时候需要用clone函数替代fork函数?


当你打算让自己的代码只在比较新的 Linux 上跑的时候。

fork 是类 Unix 系统下创建进程的标准接口;clone 是 Linux 特有的系统调用,可以对进程的创建过程提供更多的控制。
页: [1]
查看完整版本: fork()和clone()创建的进程都可以共享FD,这两个函数到底有何不同?