無限ループ内に1,2,3,...を出力させ、このループを特定のキー入力で止める。

有名な 「15 Exercises for Learning a new Programming Language」でPythonの練習。1問目。

  • fork を使ったバージョン
#!/usr/bin/env python2.5

import os
import sys
import signal
import time

pid = os.fork()

if pid == 0:
    i = 1
    while True:
        print i
        time.sleep(1)
        i = i + 1
    sys.exit()
else:
    while True:
        c = sys.stdin.read(1)
        if c == ' ':
            os.kill( pid, signal.SIGTERM )
            sys.exit()
  • Thread を使ったバージョン
#!/usr/bin/env python2.5

import sys
import time
import thread

def f():
    i=1
    while True:
        print i
        i = i + 1
        time.sleep(1)

thread.start_new_thread(f, ())

while True:
    c = sys.stdin.read(1)
    if c == ' ':
        sys.exit()

参考:jobsnake.com