#include <stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<unistd.h>
#include<string.h>
#include<pthread.h>
#include<fcntl.h>
#define BUFFER_SIZE32
#define BUF 512
charbuf[BUFFER_SIZE];
int fd;
staticpthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
staticpthread_cond_t cond = PTHREAD_COND_INITIALIZER;
//将内容写入数组
static void*thread_write(void *arg)
{
char ch;
int i;
//printf("enterthread_write\n");
while(1)
{
for(ch='A';ch<='F';ch++)
{
pthread_mutex_lock(&mutex);
for(i=0;i<BUFFER_SIZE;i++)
{
buf[i] = ch;
}
printf("%s\n",buf);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
sleep(1);
}
break;
}
printf("leave write\n");
pthread_exit(0);
}
static voidcleanup_handler(void *arg)
{
//printf("Cleanup handler of checkthread.\n");
(void)pthread_mutex_unlock(&mutex);
}
//检查写入数组的内容
static void*thread_check(void *arg)
{
char ch;
int i;
pthread_cleanup_push(cleanup_handler,&ch);
pthread_mutex_lock(&mutex);
while(1)
{
pthread_cond_wait(&cond,&mutex);
ch = buf[0];
for(i=1;i<BUFFER_SIZE;i++)
{
if(ch!=buf[i])
{
printf("checkerror\n");
break;
}
}
//检查完无误后写入fd所指向的文件
if(write(fd,buf,strlen(buf))!=strlen(buf))
//返回值与写入字节数不相等,有错误发生
{
printf("write error!!");
}
//每写完一次加锁一次
pthread_mutex_unlock(&mutex);
}
pthread_cleanup_pop(0);
printf("leave check\n");
pthread_exit(0);
}
int main(void)
{
int total_read_bytes,read_bytes,i;
char buffer1[BUF];
char buffer2[BUF];
pthread_t tid1,tid2;
//创建文件,以读写、追加的方式打开
if((fd=open("exp.c",O_RDWR|O_CREAT|O_TRUNC|O_APPEND,S_IRWXU))==-1)
{
printf("creat file error\n");
}
else
{
printf("create filesuccess\n");
}
memset(buf,0,sizeof(buf)); //数组初始化
pthread_create(&tid2, NULL,thread_check, NULL);//创建进程
pthread_create(&tid1, NULL,thread_write, NULL);
pthread_join(tid1, NULL);
sleep(1);
pthread_cancel(tid2);
pthread_join(tid2, NULL);
close(fd); //写完后关闭文件
return 0;
}