是否在fork之后由child创建了文件,也与父共享?

moh*_*hit 2 c unix linux fork

我知道之后fork(),父母打开的所有文件(及其偏移)
都由孩子共享.也就是说,共享所有文件的文件表条目.

如果孩子打开一些文件会发生什么.它是针对孩子的吗?或者由父母共享?

我也写过小测试程序.这是测试这个的正确方法吗?

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

#define FLAG (O_RDWR | O_CREAT | O_TRUNC)

int main(int argc, char *argv[])
{
    pid_t pid;

    if ((pid = fork()) < 0) {
        perror("fork error");
        exit(1);
    } else if (pid == 0) {
        int fc;
        if ((fc = open("abc", FLAG)) == -1) {
            perror("cannot open abc");
            exit(-1);
        }
        exit(fc);
        //returning the file descriptor open through exit()
    } else {
        int fp;
        wait(&fp);
        if (fp == -1)
            exit(1);
        if (fcntl(fp, F_GETFD) == -1)
            perror("doesn't work");     //Ouputs: doesn't work: Bad file descriptor
        //returns file descriptor flags
        //should not return error, if fd is valid
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

谢谢.

Joh*_*nic 5

孩子获得了父母的文件描述符的副本fork().

如果您在子项中打开文件,则不会与父项共享.

此外,如果您在父进程中打开文件后fork(),它将不与子进程共享.