10

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
    Please note that you can use change the way the memory is allocated, by running export USE_ZEND_ALLOC=0. – Pedro Cordeiro Oct 19 '15 at 16:29
12

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.

  • 1
    Does this limit count for child processes as well? For example, if I spawn an erlang REPL in this bash script, will the memory limit be imposed? – Christophe De Troyer Apr 23 '14 at 18:36
  • 2
    @ChristopheDeTroyer The limit will be inherited by child processes, so the child processes cannot exceed that. But this limit won't be applied to all process tree. – cartoonist Aug 24 '16 at 18:38

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.