Brinox
Brinox

Reputation: 37

Problems using fgets

I have to deal with an assignment and I have to use a FIFO file for IPC.

The main problem is that I´m stuck on the fget part. I´ve open the file already, but when I try to read the data stored on it, the program just stop working. It doesn´t really hungs, the program just doesn´t do anything.

I´m pretty sure that is a problem with the fgets syscall, because I´ve been debugging and the problem shows just only when I include the fgets() line on the code.

// ESCRITURA DENTRO DEL ARCHIVO FIFO QUE ABRIRA EJ2. //Creamos los fifos, comprobando que no existen

    mknod("fichero1", S_IFIFO|0777,0);
    fp= fopen("fichero1", "w+"); //Abrimos el archivo fifo
    if (fp==NULL){
        printf("Fallo al abrir el archivo, no se encuentra");
        exit(0);
    }
    fputs(msgrec, fp);
    fclose(fp);
    printf("El proceso P2 ha creado el archivo fichero1 y ha esctito el mensaje ");

    fp = fopen("fichero1", "w+");


    if (fgets(msgre, sizeof(msgrec), fp) == NULL){
        printf("Fallo al leer el archivo");
        exit(0);
    }
    printf("\n I´m here"); // DEBUGING LINE

    //Here is how he code continues.
    /*

    printf(" Lo que esta en el earchivo que es: %s \n", msgre);
    printf("%s \n", msgrec);





    execv("Ej2", 0); //Ejecucion del archivo Ej2
    */

}

Upvotes: 0

Views: 519

Answers (2)

SzG
SzG

Reputation: 12619

I assume you're on a Unix/Linux system. You could replace the library calls fopen, fputs, fgets with the corresponding raw system calls open, write, read and see what happens. The system calls don't do any user-space buffering, so it might be easier to debug.

The main trick with FIFOs is that the open syscall blocks until the other end of the FIFO is opened as well.

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201437

Change your second fopen call from a write-append mode fp = fopen("fichero1", "w+"); to

fp = fopen("fichero1", "r"); /* read mode */

I, also notice this -

if (fgets(msgrec, sizeof(msgrec), fp) == NULL){ // msgrec, not msgre.

Upvotes: 2

Related Questions