Hi all,

I've run into some strange problems when forking child processes and
logging it in a file. Here's a simplified example:

test = open("output.txt", "w")
1.upto(10) do |i|
  test.print(i.to_s + ",")
  Process.fork {sleep(10)}
  test.puts i
end
Process.waitall

Now I would expect this as output:

1,1
2,2
3,3
4,4
5,5
6,6
7,7
8,8
9,9
10,10

However, the above script produces this instead:

1,1,1
2,1,1
2,2
3,1,1
2,2
3,3
4,1,1
2,2
3,3
4,4
5,1,1
2,2
3,3
4,4
5,5
6,6
7,1,1
2,2
3,3
4,4
5,5
6,1,1
...

It goes on until both values are 10, as if there were two loops within
each other. Note that 7,1,1 appears before 6,1,1 though. I have
absolutely no idea how this is produced, but it must be caused by
forking. If I remove Process.fork I get the expected output. Also if I
open and close the file each time for writing I also get the expected
output:

1.upto(10) do |i|
  test = open("output.txt", "a")
  test.print(i.to_s + ",")
  test.close
  Process.fork {sleep(10)}
  test = open("output.txt", "a")
  test.puts i
  test.close
end
Process.waitall

I spend a lot of time figuring out, that my algorithm was in fact
working ok, but my way of writing the output was causing the problems.
I'd really like to know what's the reason this behaviour. Any
suggestions?

Regards,
 janus
-- 
Posted via http://www.ruby-forum.com/.