IO进程线程——利用线程实现文件读写

作业:

 

代码如下:

main.c

#include "head.h"

pthread_t tid1; //写线程号
pthread_t tid2; //读线程号

/**
 * @brief       写线程:向文件内写数据
 * 
 * @param arg 
 * @return void* 
 */
void* thread_write_file(void* arg)
{
    int fd = *(int*)arg; //强转接收文件描述符
    char buffer[1024] = { 0 };
    int n; //文件光标偏移变量
    while (1) {
        //清空缓冲区
        memset(buffer, 0, sizeof(buffer));

        //fgets接收数据
        fgets(buffer, sizeof(buffer), stdin);

        //判断是否接收到退出字符
        if (strncmp(buffer, "quit", 4) == 0) {
            //结束读线程
            pthread_cancel(tid2);

            //结束写线程
            pthread_exit(NULL);
        }

        //向文件中写数据
        n = write(fd, buffer, strlen(buffer));

        //文件光标偏移至上一次写的位置
        lseek(fd, -n, SEEK_CUR);
    }
}

/**
 * @brief       读线程:从文件内写数据
 * 
 * @param arg 
 * @return void* 
 */
void* thread_read_file(void* arg)
{
    int fd = *(int*)arg; //强转接收文件描述符
    char buffer[1024] = { 0 };
    while (1) {
        //清空缓冲区
        memset(buffer, 0, sizeof(buffer));

        //从文件中读数据
        if (read(fd, buffer, sizeof(buffer)) == 0) {
            continue;
        }

        //打印读出的数据
        printf("Read Thread : %s", buffer);
    }
}

int main(int argc, char const* argv[])
{
    int fd; //文件描述符
    int ret; //线程创建返回值

    if (argc != 2) {
        printf("Input error,try again!\n");
        printf("use style = ./a.out filename");
        return -1;
    }

    //打开文件
    if ((fd = open(argv[1], O_RDWR | O_CREAT | O_TRUNC, 0666)) == -1) {
        PRINT_ERR("open file error");
    }

    //创建写线程
    ret = pthread_create(&tid1, NULL, thread_write_file, (void*)&fd);
    if (ret != 0) {
        errno = ret;
        PRINT_ERR("fail to create write pthread");
    }

    //创建读线程
    ret = pthread_create(&tid2, NULL, thread_read_file, (void*)&fd);
    if (ret != 0) {
        errno = ret;
        PRINT_ERR("fail to create read pthread");
    }

    //释放写线程资源
    pthread_join(tid1,NULL);
    
    //释放读线程资源
    pthread_join(tid2,NULL);

    //关闭文件
    close(fd);

    return 0;
}

head.h

#ifndef __HEAD_H_
#define __HEAD_H_

#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <pthread.h>

#define PRINT_ERR(msg) \
    do {               \
        perror(msg);   \
        return -1;     \
    } while (0);

#endif

执行效果如下:

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值