我在构建代码时遇到了困难:
#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
从子进程打印。
我应该怎么办?