fork and sleep

Started by ghfischer, May 10, 2005, 04:09:20 PM

Previous topic - Next topic

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.

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

(SleepMe 50)


Gord

Lutz

#1
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.

#!/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