HungDev
HungDev

Reputation: 43

fprintf and printf output order differs between the console and a file

I have a difficulty when I build my code:

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv){
    char *input[2];
    input[0]= "ls";
    input[1]= "pwd";
    FILE *result;
    char *output = "output.txt";
    FILE *fout = fopen(output, "w");

    if(!fout){
        fprintf(stderr, "Can not read %s file\n", output);
        return EXIT_FAILURE;
    }

    char command[256];
    pid_t pid = 1;
    int num = 0;
    while(num < 2)
    {
        pid = fork();
        if(pid == 0){
            result = popen(input[num], "r");
            char getline[256];
            while(fgets(getline, 256, result) != NULL){
                fprintf(fout, getline);
                printf("%s", getline);
            }
            printf("\n");
        }
        else if( pid > 0){
            fprintf(fout, "#command %d\n", num);
            printf("#command %d\n", num );
            wait(NULL);
        }
        else{
            printf(stderr, "something wrong in process!");
            break;
        }
        num++;
    }

    if(pid > 0){
        pclose(result);
        fclose(fout);
    }

    return EXIT_SUCCESS;
}

I put fprintf() adjacent to printf() but result is different.

I get the following on my console:

#command 0
Debug
main.c
output.txt

#command 1
#command 1
/home/lightning/workspace/prac

/home/lightning/workspace/prac

In output.txt file:

Debug
main.c
output.txt
#command 1
#command 0
/home/lightning/workspace/prac
Debug
main.c
output.txt
/home/lightning/workspace/prac

Can anyone explain to me?

I would like the following output:

#command 0
Debug
main.c
output.txt
#command 1
/home/lightning/workspace/prac

#commnad NUM is printed from the parent process and the result of #command NUM is printed from the child process.

What should I do?

Upvotes: 0

Views: 928

Answers (1)

Dan Pichelman
Dan Pichelman

Reputation: 2332

It's been a long time since I coded in C, but if I read this correctly, you're opening a single text file, forking off a child process (which will run in parallel, more or less), having both processes independently and asynchronously write to that file, then exit.

Most likely the two process are writing all over each other on a character-by-character basis.

You have a couple of choices:

  1. re-think your logic and have each process write to its own file
  2. use file locks; have each process open the file for exclusive write (not a good idea)
  3. use locks within your code so the child process is forced to wait until the parent process finishes writing (again, not a good idea.)

Upvotes: 2

Related Questions