问题描述
- 各位大侠,小弟练习写了个代码,求解答
-
为什么运行的结果不能输出“>”,而且当我在终端输入quit时 出现不停打印“>”的死循环
代码如下:#include
#include
#include
#include
#include
#include
#include
#include#define MAX 1024
pthread_mutex_t rwlock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t rwcond =PTHREAD_COND_INITIALIZER;
void* read_file(void *arg)
{
int fd;
int ret,n;
char buf[MAX];
if(fd = open ((char *)arg ,O_CREAT|O_RDONLY,0666) == -1)
{
perror("open fail");
pthread_exit(NULL);
}
while(1){
ret =pthread_mutex_lock(&rwlock);
if (ret != 0)
{
perror("pthread_mutex_lock");
close(fd);
pthread_exit(NULL);
}
n = read(fd ,buf,sizeof(buf));
if(n< 0)
{
perror("read fail");
close(fd);
pthread_exit(NULL);
}
while(n == 0)
{
ret = pthread_cond_wait(&rwcond,&rwlock);
if(ret != 0)
{
perror("pthread_cond_wait fail");
close(fd);
pthread_exit(NULL);
}} buf[n] =''; printf("read %d character :%s n",strlen(buf),buf); if(strncmp(buf,"quit",4) == 0) { ret =pthread_mutex_unlock(&rwlock); if(ret !=0) { perror("pthread_mutex_unlock fail"); close(fd); pthread_exit(NULL); } break; } ret = pthread_mutex_unlock(&rwlock); if(ret != 0) { perror("pthread_mutex_unlock fail"); close(fd); pthread_exit(NULL); } } close(fd); pthread_exit(NULL);
}
void* write_file(void arg)
{
int fd;
int ret,n;
char buf[MAX];
char buf_bak[MAX];
fd = open((char)arg,O_CREAT|O_TRUNC|O_WRONLY,0666);
if(fd < 0)
{
perror("open fail");
pthread_exit(NULL);
}
while(1){
ret = pthread_mutex_lock(&rwlock);
if(ret != 0)
{
perror("pthread_mutex_lock fail");
close(fd);
pthread_exit(NULL);
}
printf(">n");
fgets(buf,strlen(buf),stdin);
//snprintf(buf_bak,sizeof(buf_bak),"%s",buf);
buf[strlen(buf)-1] ='';
n = write(fd,buf,sizeof(buf));
if(n < 0)
{
perror("write fail");
close(fd);
pthread_exit(NULL);
}
if(strncmp(buf,"quit",4) == 0)
{
ret = pthread_mutex_unlock(&rwlock);
if(ret != 0)
{
perror("pthread_mutex_unlock fail");
close(fd);
pthread_exit(NULL);
}
ret = pthread_cond_signal(&rwcond);
if(ret != 0)
{
perror("pthread_cond_signal fail");
close(fd);
pthread_exit(NULL);
}
usleep(500);
break;
}
ret = pthread_mutex_unlock(&rwlock);
if(ret != 0)
{
perror("pthread_mutex_unlock fail");
close(fd);
pthread_exit(NULL);
}
ret =pthread_cond_signal(&rwcond);
if(ret != 0)
{
perror("pthread_cond_signal fail");
close(fd);
pthread_exit(NULL);
}
usleep(500);
}
close(fd);
pthread_exit(NULL);
}int main (int argc,char *argv[])
{
pthread_t rpth_id,wpth_id;
int ret;
if(argc < 2)
{
fprintf(stderr,"usage: %s argv[1]n",argv[0]);
exit(EXIT_FAILURE);
}
ret = pthread_create(&rpth_id,NULL,read_file,(void *)argv[1]);
if(ret != 0)
{
perror("prhread_create fail");exit(EXIT_FAILURE);
}
usleep(500);
ret = pthread_create(&wpth_id,NULL,write_file,(void *)argv[1]);
if (ret != 0)
{
perror("pthread_create fail");
exit(EXIT_FAILURE);
}pthread_join(rpth_id,NULL); pthread_join(wpth_id,NULL); return 0;
}
解决方案
看看是不是线程没有正确退出