fork and sleep

Q&A's, tips, howto's
Locked
ghfischer
Posts: 14
Joined: Mon May 09, 2005 4:17 pm
Location: Austin, tX

fork and sleep

Post 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

Lutz
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Post 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

Locked