Skip to content

Instantly share code, notes, and snippets.

@jg75
Created July 9, 2015 17:43
Show Gist options
  • Save jg75/20c92eb52f84f142ca67 to your computer and use it in GitHub Desktop.
Save jg75/20c92eb52f84f142ca67 to your computer and use it in GitHub Desktop.
import os
import logging
from math import sqrt
def generate_primes(number):
logger = logging.getLogger(str(os.getpid()) + ':logger')
for num in range(number + 1):
# prime numbers are greater than 1
if num > 1:
for i in range(2,int(sqrt(num)+1)):
if (num % i) == 0:
break
else:
logger.info(num)
def start_workers():
logger = logging.getLogger('parent:prime')
logger.info('parent forking')
for child in range(10):
pid = os.fork()
if pid == 0:
logger = logging.getLogger(str(os.getpid()) + ':logger')
fh = logging.FileHandler('logs/child_primes_' + str(os.getpid()) + '.log')
logger.addHandler(fh)
generate_primes(1000000)
os._exit(0)
if __name__ == "__main__":
logging.basicConfig(filename='logs/parent_primes.log', level=logging.INFO)
logger = logging.getLogger('parent:prime')
logger.info('Fork parent/child logging example.')
logger.info('Starting children')
start_workers()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment