进程创建fork--文件表项继承

进程创建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#

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

spark'code

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值