甚至我的主要功能都没有运行

Not even my main fuction runs

我什至无法在屏幕上打印 "Main"。我的代码似乎运行了 none。当我不指定任何命令行参数时打印出警告。我的输入文件每行都包含整数。

#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);
    }
}

您可以在 main

的末尾添加 exit(0)

exit(0) 所做的是刷新所有缓冲区,(以及其他好东西)确保任何被缓冲的东西(比如 "Main" 的 printf)被写出。

All C streams (open with functions in <cstdio>) are closed (and flushed, if buffered), and all files created with tmpfile are removed.

http://www.cplusplus.com/reference/cstdlib/exit/