使用文件IO 实现父进程向子进程发送信息,并总结中间可能出现的各种问题

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

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


int main(int argc, const char *argv[])
{
    
    int fp1 = open("./demo.txt",O_WRONLY | O_CREAT | O_TRUNC,0664);
    if(fp1 == -1)
    {
        perror("Error open");
        return 1;
    }

    int  fp2 = open("./demo.txt",O_RDONLY,0664);
    if(fp2 == -1){
        perror("Error open");
        return 1;
    }

    int res = fork();
    if(res == -1){
        perror("Error");
        return 1;
    }
    if(res > 0){
        //主线程
        printf("父进程:");
        char a[30];
        scanf("%s",a);
        int i = write(fp1,a,sizeof(a));
        if(i == -1){
            perror("Error wrirte");
        }
        wait(NULL);
    
    }else{
        //子线程
        sleep(4);
        putchar(10);
        while(1){
            char b[100];
            int j = read(fp2,b,sizeof(b));
            if(j<= 0){
                //perror("Error read");
                break;
            }
            printf("子进程接收:%s",b);
        }
        wait(NULL);
    }
    close(fp1);
    close(fp2);
    return 0;
}
 

可能出现子进程抢夺时间片,先出现

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值