Page 1 of 1

fork and sleep

Posted: Tue May 10, 2005 11:09 pm
by ghfischer
Can someone explain to me why the following code does not sleep 5 seconds?
I have a hunch that a signal from the forked child invalidates the sleep - but I have no proof.

Code: Select all

(define (SleepMe x) 
  (println "Starting...")
  (fork (dotimes (y 10) (println y)))
  (sleep (* x 1000))
  (println "Why do you not sleep?")
)

(SleepMe 50)
Gord

Posted: Wed May 11, 2005 12:21 am
by Lutz
This is a known UNIX phenomenon. SIGCHLD interrupts sleep(). The workaround is:
don't let the thread return, but let it sleep itself until killed by the process forking it.

Code: Select all

#!/usr/bin/newlisp

(import "/usr/lib/libc.dylib" "kill") ; on Mac OSX

(define (SleepMe)
  (println "Starting...")
  (set 'pid (fork (begin
                (dotimes (y 10) (println y)) 
                (sleep 10000))))
)

(SleepMe)

(println "sleeping ...")
(sleep 2000)
(println "finished sleeping")
(kill pid 9)

(exit)
Lutz