fork后父子进程共享文件描述符
测试程序
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
#define BUFFSIZE 4096
int printFdInfo(int fd);
int main(void)
{
int fd = open("./test.cap",O_RDWR);
if(-1 == fd){
printf("file openerror\n");
return -1;
}
pid_t pid;
if ((pid = fork()) < 0) {
printf("fork error");
} else if (pid == 0) { /* child */
printf("*********************child*******************\n");
printFdInfo(fd);
printf("child seek %d\n",lseek(fd,3,SEEK_CUR));
printf("*********************child*******************\n");
} else {
sleep(2); /* parent */
printf("*********************child*******************\n");
printFdInfo(fd);
printf("parent seek cur %d\n",lseek(fd,0,SEEK_CUR));
printf("*********************child*******************\n");
}
return 0;
}
int printFdInfo(int fd)
{
struct stat sb;
if (fstat(fd, &sb) == -1) {
perror("stat");
exit(EXIT_FAILURE);
}
printf("File type: ");
switch (sb.st_mode & S_IFMT) {
case S_IFBLK: printf("block device\n"); break;
case S_IFCHR: printf("character device\n"); break;
case S_IFDIR: printf("directory\n"); break;
case S_IFIFO: printf("FIFO/pipe\n"); break;
case S_IFLNK: printf("symlink\n"); break;
case S_IFREG: printf("regular file\n"); break;
case S_IFSOCK: printf("socket\n"); break;
default: printf("unknown?\n"); break;
}
printf("I-node number: %ld\n", (long) sb.st_ino);
printf("Mode: %lo (octal)\n",
(unsigned long) sb.st_mode);
printf("Link count: %ld\n", (long) sb.st_nlink);
printf("Ownership: UID=%ld GID=%ld\n",
(long) sb.st_uid, (long) sb.st_gid);
printf("Preferred I/O block size: %ld bytes\n",
(long) sb.st_blksize);
printf("File size: %lld bytes\n",
(long long) sb.st_size);
printf("Blocks allocated: %lld\n",
(long long) sb.st_blocks);
printf("Last status change: %s", ctime(&sb.st_ctime));
printf("Last file access: %s", ctime(&sb.st_atime));
printf("Last file modification: %s", ctime(&sb.st_mtime));
return 0;
}
测试结果
*********************child*******************
File type: regular file
I-node number: 212320098
Mode: 100644 (octal)
Link count: 1
Ownership: UID=72 GID=72
Preferred I/O block size: 4096 bytes
File size: 120303 bytes
Blocks allocated: 240
Last status change: Sun Apr 8 13:45:37 2018
Last file access: Sun Apr 8 13:45:47 2018
Last file modification: Sun Apr 8 13:45:37 2018
child seek 3 //子修改文件偏移地址
*********************child*******************
*********************parent*******************
File type: regular file
I-node number: 212320098
Mode: 100644 (octal)
Link count: 1
Ownership: UID=72 GID=72
Preferred I/O block size: 4096 bytes
File size: 120303 bytes
Blocks allocated: 240
Last status change: Sun Apr 8 13:45:37 2018
Last file access: Sun Apr 8 13:45:47 2018
Last file modification: Sun Apr 8 13:45:37 2018
parent seek cur 3 //父进程的偏移地址也修改了
*********************parent*******************
总结
fork后父子进程共享一个文件描述符,父进程、子进程对文件操作都会影响对方。