Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

How to impose memory limits on a shell script?

Writer Matthew Martinez

I have a PHP script that, while a folder contains XML files, will process them onto the database.

Currently, the server is running PHP version 5.3.10 and there's a bug report about memory issues triggered by ZEND_MM_HEAP within a loop.

This causes the PHP to not free memory properly, thus leading to an error and a script crash:

 zend_mm_heap is corrupted

Some solutions are found, but I don't have access to the server settings.

To deal with this, I've prepared the following bash script to take care of the loop, leaving the PHP script only responsible by processing the XML file:

#!/bin/bash
# Check for files to process
# If files are present, call
# the PHP script
DIR="/path/to/dir/with/files"
while [ "$(ls -A $DIR)" ]; do php /path/to/php/script/myscript.php
done

My goal now is to have this bash memory allocation limited (memory and virtual memory), thus preventing it to hang the system if something goes wrong.

My Question is:
How can I limit the memory used by this shell script to a specific amount?

1

1 Answer

You can limit the memory usage by a Bash Script, doing the follow.

Limit the memory usage by kb (2GB in this example):

ulimit -m 2048000

Limit virtual memory usage:

ulimit -v 2048000

Set virtual memory limit to be hard limit, so that process will be killed when exceeding this limit:

ulimit -H -v

I think this can do what you want.

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy