父子进程对文件的操作

1.子进程继承父进程中打开的文件

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

int main(void)
{
        int fd = -1;
        pid_t pid = -1;

        fd = open("1.txt",O_RDWR | O_CREAT | O_TRUNC);
        if(fd < 0)
        {
                perror("open");
                return -1;
        }
        //fork创建子进程
        pid = fork();
        if(pid > 0)     //父进程
        {
                printf("parent \n");
                write(fd,"hello",5);
        }
        else if(pid == 0)       //子进程
        {
                printf("child \n");
                write(fd,"world",5);
        }
        else
        {
                perror("fork");
                exit(-1);
        }
	 
	    close(fd);
        return 0;
}

结果:大多数是helloworld、有时是worldhello、或world、或hello

(1)测试结果是接续写,本质上是因为父子进程之间的fd对应的文件指针是彼此有关联的(像被O_APPEND标志后的样子)
(2)有时只看到一个单词时,有点像分别写,但时间不是,原因是可能在子进程或父进程在还没有执行这个程序之前文件已经关闭。

2.父子进程各自独立打开同一文件实现共享

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

int main(void)
{
        int fd = -1;
        pid_t pid = -1;

        //fork创建子进程
        pid = fork();
        if(pid > 0)     //父进程
        {
                fd = open("1.txt",O_RDWR | O_APPEND | O_TRUNC);
                if(fd < 0)
                {
                        perror("open");
                        return -1;
                }
                printf("parent \n");
                write(fd,"hello",5);
                sleep(1);
        }
        else if(pid == 0)       //子进程
        {
                fd = open("1.txt",O_RDWR | O_APPEND | O_TRUNC);
                if(fd < 0)
                {
                        perror("open");
                        return -1;
                }
                printf("child \n");
                write(fd,"world",5);
                sleep(1);
        }
        else
        {
                perror("fork");
                exit(-1);
        }
        close(fd);
        return 0;
}

测试结果为分别写:原因是父子进程分离后才各自打开1.txt,这时两个进程的PCB已经完全独立,文件表也独立了,因此两次读写是完全独立的。但是加上O_APPEND可以把父子进程进程各自独立打开的fd的文件指针给关联起来,实现接续写。

3.总结
(1)子进程的最终目的是要独立去运行另外的程序
(2)父进程在没有fork前,自己做的事情对子进程有很大影响,fork后在自己的if里做的事情就对子进程没有影响力。本质原因是因为fork内不实际上已经复制父进程的PCB生成了一个新的子进程,并且fork返回时子进程已经完全和父进程脱离并独立被OS调度执行。

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值