Incorrect use of Process.terminate API Low

If a process that uses shared resources is terminated using Process.terminate(), then an exception might be thrown when another process attempts to use those shared resources.

Detector ID
python/incorrect-usage-of-process-terminate-api@v1.0
Category
Common Weakness Enumeration (CWE) external icon
-

Noncompliant example

1def put_object_to_queue_noncompliant(queue):
2    try:
3        queue.put([42, None, 'hello'])
4    finally:
5        queue.task_done()
6
7
8def shared_queue_noncompliant():
9    from multiprocessing.context import Process
10    from multiprocessing.queues import Queue
11    queue = Queue()
12    process = Process(target=put_object_to_queue_noncompliant, args=(queue,))
13    process.start()
14    print(queue.get())  # prints "[42, None, 'hello']"
15    # Noncompliant: uses 'Process.terminate' API on shared resources making
16    # queue liable to become corrupted and may become unusable by other process
17    process.terminate()
18    # trying to access corrupt queue
19    queue.put([50, None, 'hello'])

Compliant example

1def put_object_to_queue_compliant(queue):
2    try:
3        queue.put([42, None, 'hello'])
4    finally:
5        queue.task_done()
6
7
8def shared_queue_compliant():
9    from multiprocessing.context import Process
10    from multiprocessing.queues import Queue
11    queue = Queue()
12    process = Process(target=put_object_to_queue_compliant, args=(queue,))
13    process.start()
14    print(queue.get())  # prints "[42, None, 'hello']"
15    # Compliant: avoids using 'Process.terminate' API on shared resources
16    # making the queue accessible.
17    queue.join()
18    # accessing safe queue object
19    queue.put([50, None, 'hello'])