作业:
代码如下:
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
执行效果如下: