我正在使用 putty 运行以下代码,预期的行为应该如下:当负责读取文件的线程结束时,负责计时器的另一个线程也必须结束并反转:如果负责计时器已经结束,另一个也必须结束。但是我得到了这个致命的错误:Server unexpectedly closed network connection
当还剩一分钟时。我做错了什么?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
/* global variables to check the state*/
int read = 0;
int timeLeft = 0;
void *readFromFile(void *myFile)
{
int state;
char *theFile;
theFile = (char*) myFile;
char question[100];
char answer[100];
state = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL );
FILE *file = fopen(theFile, "r");
if (file != NULL )
{
while (fgets(question, sizeof question, file) != NULL )
{
fputs(question, stdout);
scanf("%s", &answer);
}
fclose(file);
state = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL );
printf("Done with questions!\n");
read = 1;
}
else
{
perror(theFile);
}
}
void displayTimeLeft(void *arg)
{
int *time;
int state;
time = (int*) arg;
int i;
state = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL );
for (i = time; i >= 0; i -= 60)
{
if (i / 60 != 0)
{
printf("You have %d %s left.\n", i / 60,
(i / 60 > 1) ? "minutes" : "minute");
sleep(60);
}
else
{
state = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL );
printf("The time is over \n");
timeLeft = 1;
break;
}
}
}
int main()
{
pthread_t thread1;
pthread_t thread2;
char *file = "/home/osystems01/laura/test";
int *time = 180;
int ret1;
int ret2;
ret1 = pthread_create(&thread1, NULL, readFromFile, file);
ret2 = pthread_create(&thread2, NULL, displayTimeLeft, time);
printf("Main function after pthread_create\n");
while (1)
{
if (read == 1)
{
pthread_cancel(thread2);
pthread_cancel(thread1);
break;
}
else if (timeLeft == 1)
{
pthread_cancel(thread1);
pthread_cancel(thread2);
break;
}
}
printf("After the while loop!\n");
return 0;
}