Search code examples
cmultithreadingfilepthreadsfgets

C: fgets error during multiple pthread


My overall goal of the program is to read data (float or letter) from the file and change my global constant using mutex. (I have not applied it until now)

But before I could do that, I simply thought of creating a basic program to read the entire content of the file and print to the screen. Currently, my program is unable to do so. It simply reads the first character of the file and exits the file.
I am providing my code and also the error. Any assistance will be very helpful.

#include <stdio.h>
#include <pthread.h>
#include <string.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
char *files[] = {"one.in", "two.in", "three.in", "four.in", "five.in"};

void* thread( void * arg )
{
    char * file = (char *) arg;
    // open the file and read the content
    FILE *fp = fopen(file,"r");
    char line[1024];
    int len;

    printf("Thread id is %s enter\n",file);
    if( !fp)
    {
        printf("%s file open failed\n", file);
        return 0;
    }
    else
        printf("%s File open success %p %d\n", file, fp, ftell(fp));
    // dump the file content with thread id (file name)
    while (fgets(line,len, fp))
    {
        printf("%s %s", file, line);
    }
    printf("Thread id is %s %d exit\n",file, ftell(fp));
    fclose(fp);
    return 0;
}

int main( void )
{
    int i = 0;

    if (pthread_mutex_init(&mutex, NULL) != 0)
    {
        printf("\n mutex init failed\n");
        return 1;
    }
    for(i = 4; i >= 0; i--)
    {
        pthread_t  id;
        pthread_create( &id, NULL, &thread, files[i] );
        pthread_detach(id);
    }
    printf("Main thread exit\n");
    pthread_exit(0);
    printf("Main thread real exit\n");
    return 0;
}

Errors

Thread id is five.in enter
five.in File open success 0x7fff7a2e7070 0
Thread id is five.in 0 exit
Thread id is four.in enter
four.in File open success 0x7fff7a2e7070 0
Thread id is four.in 0 exit
Thread id is three.in enter
three.in File open success 0x7fff7a2e7070 0
Thread id is three.in 0 exit
Thread id is two.in enter
two.in File open success 0x7fff7a2e7070 0
Thread id is two.in 0 exit
Thread id is one.in enter
one.in File open success 0x7fff7a2e7070 0
Thread id is one.in 0 exit
Main thread exit

File Format

R
1
2
3
-4
-5
4
W

Solution

  • The problem is the call to fgets():

    while (fgets(line,len, fp))
    

    len is uninitialized. Thi is technically undefined behaviour.

    What you want is to use the size of line:

    while (fgets(line, sizeof line, fp))