简体   繁体   中英

C program exits before logging

I've run into stuff like this before but usually just when dealing with stdout .

#define LOG 1

static void logoutput(char *info) {
    FILE *dbg;
    dbg = fopen(LOGFILE, "a+");
    if(dbg != NULL) {
        fprintf(dbg, "Mix%d: %s\n", MIXNUM, info);
        fclose(dbg);
    }
    else printf("Error writing to log file.\n");
    return;
}

if (data[0] != NULL) {
    if(LOG) logoutput("WARNING, something bad happened on port 1!");
    exit(1); //Adding a sleep(1); before this didn't help.
}

The problem I'm having is that when data[x] != NULL , the program exits immediately and never logs anything.

I tried adding a sleep(1); but that didn't do the trick. I searched around but couldn't come up with the right terms. What's the best way to handle this?

Why not try the following code?

#define LOG 1

static int logoutput(char *info) {
    FILE *dbg = NULL;
    dbg = fopen(LOGFILE, "a+");
    if(dbg != NULL) {
        fprintf(dbg, "Blah%d: %s\n", PARTNUM, info);
        fclose(dbg);
    }
    else {
        printf("Error writing to log file.\n");
    }
    return 0;//all good!
}    

static void logoutput_exit(char *info) {
   while(logoutput(info) != 0);
   exit(1);
}

if (data[0] != NULL) {
    if(LOG) logoutput_exit("WARNING, something bad happened on port 1!");
    //Adding a sleep(1); before this didn't help.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM