#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<pthread.h>
#include<errno.h>
#include<fcntl.h>
//读线程 子线程执行
void *thread_read(void *arg)
{
char buf[100] = {0};
int fd = *(int *)arg;
int n = 0;
while(1)
{
memset(buf,0,sizeof(buf));
n = read(fd,buf,sizeof(buf));
if(n == 0)
{
continue;
}
printf("Read:%s",buf);
if(strncmp(buf,"quit",4) == 0)
{
pthread_cancel(fd);
break;
}
}
}
//写线程 主线程执行
void thread_write(int fd)
{
char buf[100] = {0};
int n = 0;
while(1)
{
memset(buf,0,sizeof(buf));
fgets(buf,sizeof(buf),stdin);
n = write(fd,buf,strlen(buf));
lseek(fd,-n,SEEK_CUR);
if(strncmp(buf,"quit",4) == 0)
break;
}
}
int main(int argc, const char *argv[])
{
int fd;
pthread_t tid1,tid2;
int ret;
if(argc != 2)
{
fprintf(stderr,"usage:%s filename\n",argv[0]);
return -1;
}
//打开文件
fd = open(argv[1],O_RDWR | O_CREAT | O_TRUNC,0666);
if(fd < 0)
{
perror("Fail to open");
return -1;
}
//创建读线程
ret = pthread_create(&tid1,NULL,thread_read,(void *)&fd);
if(ret != 0)
{
errno = ret;
perror("Fail to pthread_create");
return -1;
}
ret = pthread_create(&tid2,NULL,thread_read,(void *)&fd);
if(ret != 0)
{
errno = ret;
perror ("Fail to pthread_create");
return -1;
}
//写线程
thread_write(fd);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
close(fd);
return 0;
}
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<errno.h>
void *thread_file(void *arg)
{
char *p = "0x78";
char buf[100] = {0};
while(1)
{
fgets(buf,sizeof(buf),stdin);
fputs(buf,stdout);
if(strncmp(buf,"quit",4) == 0)
break;
}
}
int main(int argc, const char *argv[])
{
pthread_t tid;
int ret;
char *retval = NULL;
ret = pthread_create(&tid,NULL,thread_file,NULL);
if(ret != 0)
{
errno = ret;
perror("Fail to pthread_create");
return -1;
}
pthread_join(tid,(void **)&retval);
printf("retval:%s\n",retval);
return 0;
}