用多线程进行读写操作

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <semaphore.h>
sem_t sem1,sem2;
pthread_t tid1,tid2; 
char buf[100]={0};
char *p;
void *fun1(void *arg)
{
    FILE *fp1 = fopen("./1.txt","r");
    if(fp1 == NULL)
    {
        perror("fopen");
        return NULL;
    }
    while(1)
    {   
        sem_wait(&sem2);
        p = fgets(buf,sizeof(buf),fp1);
        if(p == NULL)
        {
            perror("fgets");
            break;
        }
        sem_post(&sem1);
    }
}

void *fun2(void *arg)
{
    FILE *fp2 = fopen("./2.txt","a");
    if(fp2 == NULL)
    {
        perror("fopen");
        return NULL;
    }
    while(1)
    { 
        sem_wait(&sem1);
        fputs(buf,fp2);
        fflush(fp2);
        sem_post(&sem2);
    }
}

int main(int argc
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个基于多线程的串口读写操作的Demo,该程序启动了两个线程,一个线程用于读取串口数据,另一个线程用于将读取到的数据写入文件中。 ```c #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <fcntl.h> #include <termios.h> #include <unistd.h> #define MAX_BUF_SIZE 1024 char buf[MAX_BUF_SIZE]; int buf_pos = 0; void *read_thread(void *arg) { int fd = *(int *)arg; while (1) { char ch; int n = read(fd, &ch, 1); if (n > 0) { if (ch == '\n') { buf[buf_pos++] = '\0'; buf_pos = 0; } else { buf[buf_pos++] = ch; } } } } void *write_thread(void *arg) { int fd = *(int *)arg; FILE *fp = fopen("output.txt", "w"); while (1) { if (buf_pos > 0) { fprintf(fp, "%s\n", buf); fflush(fp); buf_pos = 0; } } fclose(fp); } int main() { int fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY); struct termios options; tcgetattr(fd, &options); cfsetispeed(&options, B9600); cfsetospeed(&options, B9600); options.c_cflag |= (CLOCAL | CREAD); options.c_cflag &= ~PARENB; options.c_cflag &= ~CSTOPB; options.c_cflag &= ~CSIZE; options.c_cflag |= CS8; tcsetattr(fd, TCSANOW, &options); pthread_t t1, t2; pthread_create(&t1, NULL, read_thread, &fd); pthread_create(&t2, NULL, write_thread, &fd); pthread_join(t1, NULL); pthread_join(t2, NULL); close(fd); return 0; } ``` 以上程序启动了两个线程,一个线程用于读取串口数据,另一个线程用于将读取到的数据写入文件中。其中,read_thread函数中使用read函数读取串口数据,并将读取到的数据存储在buf数组中;write_thread函数中则将buf数组中的数据写入到文件output.txt中。在主线程中,首先使用open函数打开串口设备文件,然后使用tcgetattr和tcsetattr函数配置串口参数,接着使用pthread_create函数创建两个线程,使用pthread_join函数等待两个线程的结束。注意,在使用pthread_create函数创建线程时,需要指定线程函数的类型为void *(*)(void *),表示函数返回值为void *,参数为void *。在每个线程中使用的文件描述符都是主线程中打开的串口设备文件描述符。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值