I am very new to C, so please bear with me. I have been struggling with this for a very long time, and it was difficult for me to narrow down the cause of the error.
I noticed that when forcing the process and writing to a file (only the source process writes a strange thing to the file, the output is almost multiplied by the number of forks, it is difficult to explain, so I did a little test code where you can run, and this recreates the problem.
#include <stdio.h>
#include <stdlib.h>
void foo()
{
FILE* file = fopen("test", "w");
int i=3;
int pid;
while (i>0)
{
pid=fork();
if(pid==0)
{
printf("Child\n");
exit(0);
}
else if(pid > 0)
{
fputs("test\n", file);
i=i-1;
}
}
}
int main()
{
foo();
exit(EXIT_SUCCESS);
}
Compile and run it once as is, and once with file=stdout. When writing to stdoutoutput:
test
test
test
But when writing to a file, the output is:
test
test
test
test
test
test
Also, if you add indexing and change ito a larger number, you may see some kind of pattern, but that does not help me.
, , , , . C, =).
.