0

我在构建代码时遇到了困难:

#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;
}

我把fprintf()相邻printf()但结果不同。

我在控制台上得到以下信息:

#command 0
Debug
main.c
output.txt

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

/home/lightning/workspace/prac

output.txt文件中:

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

谁能给我解释一下?

我想要以下输出:

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

#commnad NUM从父进程打印,结果#command NUM从子进程打印。

我应该怎么办?

4

1 回答 1

2

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.)
于 2012-09-13T16:51:25.770 回答