进程创建fork–文件表项继承
子进程继承父进程的文件描述表,不继承共享文件表项和iNode。
父进程创建一个子进程后,文件表项中的引用计数器加1变为2,当父进程操作close操作后,计数器减1,子进程还是可以使用文件表项,只有当计数器为0时,才会释放文件表项。
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
/*
*
* 在父进程中将文件定位到结尾处,在子进程中追加文本
* ./fork_file forkfile.txt XXXXX
*
*/
int main(int argv, char *argc[])
{
int fd;
pid_t pid;
char *buf;
if(argv < 3) {
printf("argv is wrong.....\n");
return -1;
}
fd = open(argc[1], O_WRONLY);
buf = argc[2];
printf("buf: %s\n", buf);
pid = fork();
if (pid < 0) {
printf("fork fail.\n");
return -1;
} else if (pid > 0) {
lseek(fd, 0, SEEK_END);
} else {
sleep(3);
/* 此处的fd为子进程继承(复制)父进程的文件描述符,与父进程中不是同一个,但是内容指向是相同的*/
printf("write buf: %s\n", buf);
if (write(fd, buf, strlen(buf)) != strlen(buf)) {
printf("write buf to fd fail. len_buf:%ld\n", strlen(buf));
return -1;
}
}
/* 此处之后的代码会执行两遍,父进程和子进程各一遍 */
sleep(2);
printf("pid: %d finish.\n", getpid());
close(fd);
return 0;
}
运行结果:
root@spark# ./fork_file forkfile.txt ccccc
pid: 3172 finish.
write buf: ccccc
pid: 3173 finish.
root@spark#