我知道之后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)
谢谢.