Я даже не могу распечатать «Main» на экране. Кажется, что ни один из моих кодов не работает. Когда я не укажу какие-либо аргументы командной строки при выводе предупреждения. мой входной файл содержит целые числа в каждой строке.Даже мои основные ходы fuction
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>
#include <sys/types.h>
int patientCount,treatedPatientCount,maxPatient,allRegistered;
int *list;
FILE *input,*output;
sem_t semOutputFile,semGlobalVars;
void* Nurse();
void* Doctor(void *);
int main(int argc, char *argv[]){
printf("Main");
if(argc != 3){
printf("Command line argument count is different then expected. Aborting!");
return -1;
}
input = fopen(argv[1],"r");
output = fopen(argv[2],"w");
allRegistered = 0;
maxPatient = 5;
treatedPatientCount = 0;
patientCount = 0;
list = malloc(sizeof(int)*maxPatient);
pthread_t nurse,doc1,doc2;
sem_init(&semGlobalVars, 0, 1);
sem_init(&semOutputFile, 0, 1);
pthread_create(&nurse, NULL, &Nurse, NULL);
pthread_create(&doc1, NULL, &Doctor, (void*) 1);
pthread_create(&doc2, NULL, &Doctor, (void*) 2);
pthread_exit(NULL);
}
void* Nurse(){
char buff[255],*eof;
while(1){
eof = fgets(buff, 255, input);
if (eof == NULL) {
allRegistered = 1;
pthread_exit(NULL);
}
int k = atoi(buff);
sem_wait(&semGlobalVars);//Critical region 1 starts
if(patientCount == maxPatient){
maxPatient *=2;
list = realloc(list,sizeof(int)*maxPatient);
}
list[patientCount++] = k;
sem_post(&semGlobalVars);//Critical region 1 ends
sem_wait(&semOutputFile);//Critical region 2 starts
fputs("Nurse registered a patient!\n",output);
sem_post(&semOutputFile);//Critical region 2 ends
sleep(2);
}
}
void* Doctor(void * id){
printf("Doctor");
char buff[255];
int waitTime = 0;
while(1){
printf("%d %d %d",allRegistered,treatedPatientCount,patientCount);
if(allRegistered == 1 && treatedPatientCount==patientCount) pthread_exit(NULL);
sem_wait(&semGlobalVars);//Critical region 1 starts
waitTime = list[treatedPatientCount++];
sem_post(&semGlobalVars);//Critical region 1 ends
sprintf (buff, "Doctor %d treated a patient\n", (int) id);
sem_wait(&semOutputFile);//Critical region 2 starts
fputs(buff,output);
sem_post(&semOutputFile);//Critical region 2 ends
sleep(waitTime);
}
}
Выход на 'stdout' (что происходит, когда вы используете' printf') по умолчанию * линии забуференном *. Это означает, что вывод записывается в консоль, когда буфер заполнен * или * у вас есть новая строка. Вот почему вы всегда должны заканчивать вывод с помощью новой строки. –
... или войдите в 'stderr', используя' fprintf (stderr, ... 'вместо' printf (... '. – alk
добавить' fflush (stdout); 'после вашего' printf' – chqrlie