c - How to prevent fork from returning twice,
问题描述
so I am working on this C code, that print a list of child PID and parent PID
the problem that my output looks like this
digraph {
"12896" [ label="pid 12896, level 0" ];
"12897" [ label="pid 12897, level 1" ];
"12896" -> "12897";
"12898" [ label="pid 12898, level 2" ];
"12897" -> "12898";
"12899" [ label="pid 12899, level 3" ];
"12898" -> "12899";
"12900" [ label="pid 12900, level 4" ];
"12899" -> "12900";
}digraph {
"12896" [ label="pid 12896, level 0" ];
"12897" [ label="pid 12897, level 1" ];
"12896" -> "12897";
"12898" [ label="pid 12898, level 2" ];
"12897" -> "12898";
"12899" [ label="pid 12899, level 3" ];
"12898" -> "12899";
digraph {
"12896" [ label="pid 12896, level 0" ];
"12897" [ label="pid 12897, level 1" ];
"12896" -> "12897";
"12898" [ label="pid 12898, level 2" ];
"12897" -> "12898";
digraph {
"12896" [ label="pid 12896, level 0" ];
"12897" [ label="pid 12897, level 1" ];
"12896" -> "12897";
digraph {
there is 4 different digraph object, I only need the first one. also I am not sure why the first line inside digraph is tabbed, if anyone knows
here is the C code of my fork
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(void){
int i, status;
printf( "Enter a value for n :");
int n;
scanf("%d", &n);
FILE *file;
file = fopen("./diagraph.txt", "w+"); //my output file
fprintf(file, "digraph {\n");
for (i=0; i<=n; i++){
//fflush(stdout);
int pid = fork();
if (pid == 0 ) {
if(i == 0){ //first level
fprintf(file, " \"%d\" [ label=\"pid %d, level %d\" ];\n", getppid(), getppid(), i, file);
fprintf(file, " \"%d\" [ label=\"pid %d, level %d\" ];\n", getpid(), getpid(), i +1, file);
fprintf(file, " \"%d\" -> \"%d\";\n", getppid(), getpid(), file);
}else{
fprintf(file, " \"%d\" [ label=\"pid %d, level %d\" ];\n", getpid(), getpid(), i +1, file);
fprintf(file, " \"%d\" -> \"%d\";\n", getppid(), getpid(), file);
}
}
else{ //parent process, we will wait for the children.
pid = waitpid(-1, &status, 0);
return 0;
}
}
fprintf(file, "}");
fclose(file);
}
I am not sure of the reason of this behavior, I would like to understand it and know how to fix it thank you in advance
解决方案
默认情况下,当您使用它写入文件时,fprintf
它实际上并没有写入文件(还)——它只是写入缓冲区。当缓冲区填满时,或者您稍后调用fflush
orfclose
时,缓冲区中的数据将写入文件。缓冲区是存储在进程内存中的 FILE 对象的一部分,因此当您调用 时fork
,缓冲区及其内容会被复制。这导致子和父可能将相同的数据写入文件的情况,从而导致重复。
避免这种情况的最简单方法是确保在调用 fork 之前调用fflush
所有FILE
对象,以便缓冲区全部为空并且没有数据重复。