3
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonで シグナルをトラップするサンプルスクリプト

Posted at

目的

シグナルの勉強をしてて、SIGTERMをトラップするスクリプトをメモとして残します

参考

こちらを参考にしました
https://engineeringnote.hateblo.jp/entry/python/signal

スクリプト

signal.py
import signal
import time
from threading import Thread

FLAG = False

def handler(signum, frame):
    global FLAG
    print("signal={}".format(signum))
    FLAG = True

def waiting():
    global FLAG
    while not FLAG:
        print("Waiting for signal...")
        time.sleep(5)

t1 = Thread(target=waiting, args=[])
t2 = Thread(target=waiting, args=[])
t1.start()
t2.start()

signal.signal(signal.SIGTERM, handler)
signal.signal(signal.SIGINT, handler)
signal.pause()

挙動


python signale.py 
Waiting for signal...
Waiting for signal...

プロセスの確認

ps aux | grep test
ec2-user 21269  0.0  0.1 275896  9144 pts/1    Sl+  16:40   0:00 python36 test.py

SIGTERM の発行

kill -SIGTERM 21269

トラップされたことを確認

Waiting for signal...
Waiting for signal...
Waiting for signal...
Waiting for signal...
Waiting for signal...
Waiting for signal...
Waiting for signal...
Waiting for signal...
Waiting for signal...
Waiting for signal...
Waiting for signal...
Waiting for signal...
Waiting for signal...
Waiting for signal...
Waiting for signal...
Waiting for signal...
signal=15
3
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?