linux进程间通信练习:对于text.txt文件,子进程将字符串“something communication”写入text.txt,父进程读取text.txt文件内容并打印。

【问题描述】

使用C语言实现下述要求的程序:

1.对于text.txt文件,子进程将字符串“something communication”写入text.txt,父进程读取text.txt文件内容打印。

【程序代码】

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

void main(){
    printf("parent process is running.\n");
    int res;
    char buf_wr[] = " something communication ";
    char buf_rd[sizeof(buf_wr)];
    buf_rd[0] = '\0';
    int fd = open("/tmp/text.txt", O_RDWR | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
    if(fd < 0){
        printf("error: open file:/tmp/text.txt failed.\n");
        exit(EXIT_FAILURE);
    }
    pid_t pid = fork();
    switch(pid){
        case 0:
            // 子进程
            printf("child process is running.\n");
            res = write(fd, buf_wr, sizeof(buf_wr));
            if(res != sizeof(buf_wr)){
                printf("error: child process write failed.\n");
                exit(EXIT_FAILURE);
            }
            close(fd); // 子进程先关闭自己的文件描述符
            printf("child process was done.\n");
            exit(0);
        case -1:
            // error
            exit(EXIT_FAILURE);
        default:
        	// 父进程
        	// 父进程等待子进程终止
            wait(0);
			// 设置文件的‘读写位置’,使其偏移到子进程执行写入操作时的位置
            lseek(fd, 0 - sizeof(buf_wr), SEEK_CUR);

            res = read(fd, buf_rd, sizeof(buf_wr));
            if(res == 0){
                // EOF
                printf("EOF\n");
            }else if(res > 0){
                printf("parent process was done. readed string is '%s'\n", buf_rd);
            }else{
                // error
                printf("error: parent process read failed.\n");
                exit(EXIT_FAILURE);
            }
            close(fd);
            exit(EXIT_SUCCESS);
    }
}

【程序运行结果】

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值