0

I am tryinIg to send log-events from different threads through a FIFO, read the events and write them to a file.

First I forked my main(). In the Child I want to run the FIFO reader and in the Parent i start my threads (these works fine).

#define FIFO "logFifo"
#define MAX_BUF 1024

int main(int argc, char *argv[]){
    pid_t pid;
    pid=fork();

    if(pid<0){
        printf("error with fork() \n");exit(1);
    }

    if(pid == (pid_t) 0){
        //FIFO lezen van log_file
        int err;

        char buf[MAX_BUF];
        char * str_result;
        FILE *log;

        err = mkfifo(FIFO, 0666);
        CHECK_MKFIFO(err);

        log = fopen(FIFO, "r");
        FILE_OPEN_ERROR(log);

        while(1){
                //presult = pthread_mutex_lock( &log_mutex);
                //pthread_err_handler( presult, "pthread_mutex_lock", __FILE__);


                str_result = fgets(buf, MAX_BUF,log);


                if(str_result != NULL){

                    FILE *fp; 
                    fp = fopen("gateway.log","w");
                    fprintf(fp,"%s \n",buf);
                    //fclose(fp);
                }

                //presult = pthread_mutex_unlock( &log_mutex);
                //pthread_err_handler( presult, "pthread_mutex_unlock", __FILE__ );

                sequence++;

                //usleep(1);


        }

        //unlink(FIFO);

    }
    else{
       //Parent code}
return 0;}

I made a function that will send the log-events:

void send_log(char * message){
    FILE *log;
    int err;

    err = mkfifo(FIFO, 0666);
    CHECK_MKFIFO(err);

    log = fopen(FIFO, "w");
    FILE_OPEN_ERROR(log);

    char *msg;

    asprintf(&msg, "%d %lu %s", sequence,(unsigned long)time(NULL),message);

    printf("log message: %s \n",msg);


    if( fputs(msg,log) == EOF){
        fprintf(stderr, "error writing data to fifo \n");
        exit (EXIT_FAILURE);
    }
    FFLUSH_ERROR(fflush(log));

    free(msg);

    sequence++;

    /*err = fclose(log);
    FILE_CLOSE_ERROR(err);*/

}

I know I put some things in commment, but I tried it also with those in code. Can anyone help me out?

Thank you!

EDIT : solution was to use "aw" instead of "w" and open my gateway.log in the while loop

Gus Vanherf
  • 53
  • 1
  • 6

0 Answers0