The second of several forked processes does not start in Haskell (GHC 7.8.4)

I have a simple Haskell program that drops several processes, each of which sleeps for a certain number of seconds, and then an echo. No matter how many processes I fork, the second one does not seem to display any visible content on the terminal.

import System.Process (createProcess, proc, shell, CreateProcess) import Text.Printf (printf, PrintfArg) import Control.Concurrent (forkIO) import Control.Monad (void) sleep :: Integer -> CreateProcess sleep x = shell (printf "sleep %d; echo %d" xx) -- sleep x = shell (printf "sleep %d, echo %d, touch %d.haskell" xxx) main = foldr1 (>>) $ [ forkIO $ void $ createProcess task | task <- [ sleep 1, sleep 2, sleep 3, sleep 4, sleep 5] ] 

produces

 ./scheduler user@name-of-computer $ 1 3 4 5 

And if you run it with a commented line, and not just with print, you will see

 $ 1.haskell 4.haskell 3.haskell 5.haskell 

This behavior is also characteristic of Haskell. Perl does not show it.

 use strict; use warnings FATAL => 'all'; sub sleep_echo { my ($second_count) = @_; my $cpid = fork; if ($cpid == 0) { exec "sleep $second_count; echo $second_count"; } } for (my $i = 1; $i <= 5; $i++) { sleep_echo($i); } 

prints

 user@name-of-computer $ 1 2 3 4 5 

Any ideas on what's going on?

+1
source share
1 answer

I was able to reproduce this using GHC 7.10.2.

The versions of Haskell and Perl are not strictly equivalent. The Perl version will create the process after the process, expecting that the previous one will be launched (not completed).

The Haskell version will create multiple threads, each of which starts a single process.

Since you do not wait for your threads to complete the process, some threads will fail because your program ends too quickly. Haskell's execution of a thread at runtime is not random, so your program (as a rule) will exhibit the same behavior over and over on your computer.

You can also try to increase the number of processes to see what happens. With 14 processes, the 13th process does not start (according to my configuration).

If you delete the forkIO call, your program will work fine:

 import System.Process (createProcess, proc, shell, CreateProcess) import Text.Printf (printf, PrintfArg) import Control.Monad (void) sleep :: Integer -> CreateProcess sleep x = shell (printf "sleep %d; echo %d" xx) main = foldr1 (>>) [ void $ createProcess task | task <- fmap sleep [1..5] ] 
+2
source

Source: https://habr.com/ru/post/1271171/


All Articles