Skip to content

Instantly share code, notes, and snippets.

@c-rhodes
Created November 19, 2014 19:05
Show Gist options
  • Save c-rhodes/4abfbe0f347506cc2936 to your computer and use it in GitHub Desktop.
Save c-rhodes/4abfbe0f347506cc2936 to your computer and use it in GitHub Desktop.
# Demonstration of a time of check to time of use (toutou) race condition
import os
import time
from threading import Thread
class ReadFileThread(Thread):
def __init__(self, file_name):
self.file_name = file_name
super().__init__()
def run(self):
if os.path.isfile(self.file_name):
print('{file_name} exists'.format(file_name=self.file_name))
time.sleep(0.1)
file_contents = open(self.file_name, 'r').read()
print(file_contents)
class RemoveFileThread(Thread):
def __init__(self, file_name):
self.file_name = file_name
super().__init__()
def run(self):
print('Deleting {file_name}'.format(file_name=self.file_name))
os.remove(self.file_name)
def demonstrate_toctou_race_condition():
file_name = 'tmp'
open(file_name, 'a').close() # create empty file
read_file_thread = ReadFileThread(file_name)
remove_file_thread = RemoveFileThread(file_name)
read_file_thread.start()
remove_file_thread.start()
demonstrate_toctou_race_condition()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment