Shell-script to periodically free some memory up with Ubuntu 18.10 LiveCD with only 4GB of RAM. Need some...











up vote
0
down vote

favorite
1












Edit 1:
The freezing just happened and I was able recover from it. Log(syslog) from the freezing until 'now': https://ufile.io/ivred



Edit 2: It seems a bug/problem with GDM3. I'll try Xubuntu.



Edit 3: Now I'm using Xubuntu. The problem still happens, but a lot less often. So.. it is indeed a memory issue.



I'm currently using Ubuntu 18.10 Live CD since my HD died. I did some customizations to my LiveCD mainly towards memory consumption, because I have only 4GB of RAM.



When my free memory goes below 100MB, my pendrive LED starts to blink like crazy and the system freezes letting me time to just get out of GUI interface (ctrl + alt + f1-12) and reboot(ctrl + alt + del) or, sometimes to close Google Chrome with sudo killall chrome.



So I created a very simple script to clean the system cache and close Google Chrome. Closing Chrome out of the blue like that is fine, since it asks you to recover the tabs when it wasn't closed properly.



The question: It works like a charm 95% of the time. I don't know if my script is too simple or there is another reason for this intermittent freezing since I can't check the log, because of the need of reboot. Is there a more efficient way to do that? Am I doing it wrong?



Obs.: I have another script to clean the cache that runs every 15 minutes. Since I created those scripts I am able to use my LiveCD every day with almost no freezing. Maybe 1 per day.. Before that I had to reboot every 30-40min, because I use the Chrome with several tabs.



My script:



#!/bin/bash 

while true ; do
free=`free -m | grep Mem | awk '{print $4}'`
if [ "$free" -gt 0 ]
then
if [ $free -le 120 ]; #When my memory consuptiom goes below 120MB do the commands below.
then

if pgrep -x "chrome" > /dev/null
then
sudo killall -9 chrome
sudo su xubuntu
/usr/bin/google-chrome-stable --password-store=basic --aggressive-cache-discard --aggressive-tab-discard
else
echo "Stopped"
fi

sudo sysctl -w vm.drop_caches=3
sudo sync && echo 3 | sudo tee /proc/sys/vm/drop_caches



fi
fi & sleep 1; done









share|improve this question




















  • 1




    Do you have swap partition on pendrive? Then disable it. swapoff -a.
    – Ipor Sircer
    Nov 24 at 17:21










  • No swap partition on my pendrive.
    – Lucas Rizzini
    Nov 24 at 17:39






  • 3




    Then teach chrome to use less ram. Look at parameters, for example: --mem-pressure-system-reserved-kb=XXX, --aggressive-cache-discard, --aggressive-tab-discard, etc... 4gb is fairly enough to run chrom[e|ium] nowadays. My chromium nevers eats more than 2.6gb in any conditions (even with 50+ opened tabs).
    – Ipor Sircer
    Nov 24 at 18:23












  • use an real open source less RAM extensive browser, or maybe try to not open too much tab
    – Kiwy
    Nov 28 at 10:44












  • I need to use Google Chrome and a lot of tabs. Otherwise, I would have already changed my browser.
    – Lucas Rizzini
    Nov 28 at 12:29















up vote
0
down vote

favorite
1












Edit 1:
The freezing just happened and I was able recover from it. Log(syslog) from the freezing until 'now': https://ufile.io/ivred



Edit 2: It seems a bug/problem with GDM3. I'll try Xubuntu.



Edit 3: Now I'm using Xubuntu. The problem still happens, but a lot less often. So.. it is indeed a memory issue.



I'm currently using Ubuntu 18.10 Live CD since my HD died. I did some customizations to my LiveCD mainly towards memory consumption, because I have only 4GB of RAM.



When my free memory goes below 100MB, my pendrive LED starts to blink like crazy and the system freezes letting me time to just get out of GUI interface (ctrl + alt + f1-12) and reboot(ctrl + alt + del) or, sometimes to close Google Chrome with sudo killall chrome.



So I created a very simple script to clean the system cache and close Google Chrome. Closing Chrome out of the blue like that is fine, since it asks you to recover the tabs when it wasn't closed properly.



The question: It works like a charm 95% of the time. I don't know if my script is too simple or there is another reason for this intermittent freezing since I can't check the log, because of the need of reboot. Is there a more efficient way to do that? Am I doing it wrong?



Obs.: I have another script to clean the cache that runs every 15 minutes. Since I created those scripts I am able to use my LiveCD every day with almost no freezing. Maybe 1 per day.. Before that I had to reboot every 30-40min, because I use the Chrome with several tabs.



My script:



#!/bin/bash 

while true ; do
free=`free -m | grep Mem | awk '{print $4}'`
if [ "$free" -gt 0 ]
then
if [ $free -le 120 ]; #When my memory consuptiom goes below 120MB do the commands below.
then

if pgrep -x "chrome" > /dev/null
then
sudo killall -9 chrome
sudo su xubuntu
/usr/bin/google-chrome-stable --password-store=basic --aggressive-cache-discard --aggressive-tab-discard
else
echo "Stopped"
fi

sudo sysctl -w vm.drop_caches=3
sudo sync && echo 3 | sudo tee /proc/sys/vm/drop_caches



fi
fi & sleep 1; done









share|improve this question




















  • 1




    Do you have swap partition on pendrive? Then disable it. swapoff -a.
    – Ipor Sircer
    Nov 24 at 17:21










  • No swap partition on my pendrive.
    – Lucas Rizzini
    Nov 24 at 17:39






  • 3




    Then teach chrome to use less ram. Look at parameters, for example: --mem-pressure-system-reserved-kb=XXX, --aggressive-cache-discard, --aggressive-tab-discard, etc... 4gb is fairly enough to run chrom[e|ium] nowadays. My chromium nevers eats more than 2.6gb in any conditions (even with 50+ opened tabs).
    – Ipor Sircer
    Nov 24 at 18:23












  • use an real open source less RAM extensive browser, or maybe try to not open too much tab
    – Kiwy
    Nov 28 at 10:44












  • I need to use Google Chrome and a lot of tabs. Otherwise, I would have already changed my browser.
    – Lucas Rizzini
    Nov 28 at 12:29













up vote
0
down vote

favorite
1









up vote
0
down vote

favorite
1






1





Edit 1:
The freezing just happened and I was able recover from it. Log(syslog) from the freezing until 'now': https://ufile.io/ivred



Edit 2: It seems a bug/problem with GDM3. I'll try Xubuntu.



Edit 3: Now I'm using Xubuntu. The problem still happens, but a lot less often. So.. it is indeed a memory issue.



I'm currently using Ubuntu 18.10 Live CD since my HD died. I did some customizations to my LiveCD mainly towards memory consumption, because I have only 4GB of RAM.



When my free memory goes below 100MB, my pendrive LED starts to blink like crazy and the system freezes letting me time to just get out of GUI interface (ctrl + alt + f1-12) and reboot(ctrl + alt + del) or, sometimes to close Google Chrome with sudo killall chrome.



So I created a very simple script to clean the system cache and close Google Chrome. Closing Chrome out of the blue like that is fine, since it asks you to recover the tabs when it wasn't closed properly.



The question: It works like a charm 95% of the time. I don't know if my script is too simple or there is another reason for this intermittent freezing since I can't check the log, because of the need of reboot. Is there a more efficient way to do that? Am I doing it wrong?



Obs.: I have another script to clean the cache that runs every 15 minutes. Since I created those scripts I am able to use my LiveCD every day with almost no freezing. Maybe 1 per day.. Before that I had to reboot every 30-40min, because I use the Chrome with several tabs.



My script:



#!/bin/bash 

while true ; do
free=`free -m | grep Mem | awk '{print $4}'`
if [ "$free" -gt 0 ]
then
if [ $free -le 120 ]; #When my memory consuptiom goes below 120MB do the commands below.
then

if pgrep -x "chrome" > /dev/null
then
sudo killall -9 chrome
sudo su xubuntu
/usr/bin/google-chrome-stable --password-store=basic --aggressive-cache-discard --aggressive-tab-discard
else
echo "Stopped"
fi

sudo sysctl -w vm.drop_caches=3
sudo sync && echo 3 | sudo tee /proc/sys/vm/drop_caches



fi
fi & sleep 1; done









share|improve this question















Edit 1:
The freezing just happened and I was able recover from it. Log(syslog) from the freezing until 'now': https://ufile.io/ivred



Edit 2: It seems a bug/problem with GDM3. I'll try Xubuntu.



Edit 3: Now I'm using Xubuntu. The problem still happens, but a lot less often. So.. it is indeed a memory issue.



I'm currently using Ubuntu 18.10 Live CD since my HD died. I did some customizations to my LiveCD mainly towards memory consumption, because I have only 4GB of RAM.



When my free memory goes below 100MB, my pendrive LED starts to blink like crazy and the system freezes letting me time to just get out of GUI interface (ctrl + alt + f1-12) and reboot(ctrl + alt + del) or, sometimes to close Google Chrome with sudo killall chrome.



So I created a very simple script to clean the system cache and close Google Chrome. Closing Chrome out of the blue like that is fine, since it asks you to recover the tabs when it wasn't closed properly.



The question: It works like a charm 95% of the time. I don't know if my script is too simple or there is another reason for this intermittent freezing since I can't check the log, because of the need of reboot. Is there a more efficient way to do that? Am I doing it wrong?



Obs.: I have another script to clean the cache that runs every 15 minutes. Since I created those scripts I am able to use my LiveCD every day with almost no freezing. Maybe 1 per day.. Before that I had to reboot every 30-40min, because I use the Chrome with several tabs.



My script:



#!/bin/bash 

while true ; do
free=`free -m | grep Mem | awk '{print $4}'`
if [ "$free" -gt 0 ]
then
if [ $free -le 120 ]; #When my memory consuptiom goes below 120MB do the commands below.
then

if pgrep -x "chrome" > /dev/null
then
sudo killall -9 chrome
sudo su xubuntu
/usr/bin/google-chrome-stable --password-store=basic --aggressive-cache-discard --aggressive-tab-discard
else
echo "Stopped"
fi

sudo sysctl -w vm.drop_caches=3
sudo sync && echo 3 | sudo tee /proc/sys/vm/drop_caches



fi
fi & sleep 1; done






shell-script ubuntu chrome livecd out-of-memory






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 13 hours ago

























asked Nov 24 at 16:47









Lucas Rizzini

113




113








  • 1




    Do you have swap partition on pendrive? Then disable it. swapoff -a.
    – Ipor Sircer
    Nov 24 at 17:21










  • No swap partition on my pendrive.
    – Lucas Rizzini
    Nov 24 at 17:39






  • 3




    Then teach chrome to use less ram. Look at parameters, for example: --mem-pressure-system-reserved-kb=XXX, --aggressive-cache-discard, --aggressive-tab-discard, etc... 4gb is fairly enough to run chrom[e|ium] nowadays. My chromium nevers eats more than 2.6gb in any conditions (even with 50+ opened tabs).
    – Ipor Sircer
    Nov 24 at 18:23












  • use an real open source less RAM extensive browser, or maybe try to not open too much tab
    – Kiwy
    Nov 28 at 10:44












  • I need to use Google Chrome and a lot of tabs. Otherwise, I would have already changed my browser.
    – Lucas Rizzini
    Nov 28 at 12:29














  • 1




    Do you have swap partition on pendrive? Then disable it. swapoff -a.
    – Ipor Sircer
    Nov 24 at 17:21










  • No swap partition on my pendrive.
    – Lucas Rizzini
    Nov 24 at 17:39






  • 3




    Then teach chrome to use less ram. Look at parameters, for example: --mem-pressure-system-reserved-kb=XXX, --aggressive-cache-discard, --aggressive-tab-discard, etc... 4gb is fairly enough to run chrom[e|ium] nowadays. My chromium nevers eats more than 2.6gb in any conditions (even with 50+ opened tabs).
    – Ipor Sircer
    Nov 24 at 18:23












  • use an real open source less RAM extensive browser, or maybe try to not open too much tab
    – Kiwy
    Nov 28 at 10:44












  • I need to use Google Chrome and a lot of tabs. Otherwise, I would have already changed my browser.
    – Lucas Rizzini
    Nov 28 at 12:29








1




1




Do you have swap partition on pendrive? Then disable it. swapoff -a.
– Ipor Sircer
Nov 24 at 17:21




Do you have swap partition on pendrive? Then disable it. swapoff -a.
– Ipor Sircer
Nov 24 at 17:21












No swap partition on my pendrive.
– Lucas Rizzini
Nov 24 at 17:39




No swap partition on my pendrive.
– Lucas Rizzini
Nov 24 at 17:39




3




3




Then teach chrome to use less ram. Look at parameters, for example: --mem-pressure-system-reserved-kb=XXX, --aggressive-cache-discard, --aggressive-tab-discard, etc... 4gb is fairly enough to run chrom[e|ium] nowadays. My chromium nevers eats more than 2.6gb in any conditions (even with 50+ opened tabs).
– Ipor Sircer
Nov 24 at 18:23






Then teach chrome to use less ram. Look at parameters, for example: --mem-pressure-system-reserved-kb=XXX, --aggressive-cache-discard, --aggressive-tab-discard, etc... 4gb is fairly enough to run chrom[e|ium] nowadays. My chromium nevers eats more than 2.6gb in any conditions (even with 50+ opened tabs).
– Ipor Sircer
Nov 24 at 18:23














use an real open source less RAM extensive browser, or maybe try to not open too much tab
– Kiwy
Nov 28 at 10:44






use an real open source less RAM extensive browser, or maybe try to not open too much tab
– Kiwy
Nov 28 at 10:44














I need to use Google Chrome and a lot of tabs. Otherwise, I would have already changed my browser.
– Lucas Rizzini
Nov 28 at 12:29




I need to use Google Chrome and a lot of tabs. Otherwise, I would have already changed my browser.
– Lucas Rizzini
Nov 28 at 12:29










1 Answer
1






active

oldest

votes

















up vote
0
down vote



accepted










The solution that "fra-san" gave at the comments here fitted perfectly. Using "cgroup-tools" package I was able to limit Chrome memory usage successfully. I tested it opening dozens of tabs at the same time and I could see the memory limit in action. However, I had to leave my script running, since, as much as I mostly use Chrome, system cache consumes a lot of RAM too.



My steps:



1- Used this script from: Limit memory usage for a single Linux process



#!/bin/sh

# This script uses commands from the cgroup-tools package. The cgroup-tools commands access the cgroup filesystem directly which is against the (new-ish) kernel's requirement that cgroups are managed by a single entity (which usually will be systemd). Additionally there is a v2 cgroup api in development which will probably replace the existing api at some point. So expect this script to break in the future. The correct way forward would be to use systemd's apis to create the cgroups, but afaik systemd currently (feb 2018) only exposes dbus apis for which there are no command line tools yet, and I didn't feel like writing those.

# strict mode: error if commands fail or if unset variables are used
set -eu

if [ "$#" -lt 2 ]
then
echo Usage: `basename $0` "<limit> <command>..."
echo or: `basename $0` "<memlimit> -s <swaplimit> <command>..."
exit 1
fi

cgname="limitmem_$$"

# parse command line args and find limits

limit="$1"
swaplimit="$limit"
shift

if [ "$1" = "-s" ]
then
shift
swaplimit="$1"
shift
fi

if [ "$1" = -- ]
then
shift
fi

if [ "$limit" = "$swaplimit" ]
then
memsw=0
echo "limiting memory to $limit (cgroup $cgname) for command $@" >&2
else
memsw=1
echo "limiting memory to $limit and total virtual memory to $swaplimit (cgroup $cgname) for command $@" >&2
fi

# create cgroup
sudo cgcreate -g "memory:$cgname"
sudo cgset -r memory.limit_in_bytes="$limit" "$cgname"
bytes_limit=`cgget -g "memory:$cgname" | grep memory.limit_in_bytes | cut -d -f2`

# try also limiting swap usage, but this fails if the system has no swap
if sudo cgset -r memory.memsw.limit_in_bytes="$swaplimit" "$cgname"
then
bytes_swap_limit=`cgget -g "memory:$cgname" | grep memory.memsw.limit_in_bytes | cut -d -f2`
else
echo "failed to limit swap"
memsw=0
fi


2- Named it as "limitmem" and copied to /usr/bin/ so I could call it from terminal just with limitmem. Now I can open a process limiting the memory usage to, for example, 800MB using this syntax:limitmem 800M command



In my case: limitmem 1000M google-chrome --password-store=basic --aggressive-cache-discard --aggressive-tab-discard






share|improve this answer























    Your Answer








    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "106"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f483898%2fshell-script-to-periodically-free-some-memory-up-with-ubuntu-18-10-livecd-with-o%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote



    accepted










    The solution that "fra-san" gave at the comments here fitted perfectly. Using "cgroup-tools" package I was able to limit Chrome memory usage successfully. I tested it opening dozens of tabs at the same time and I could see the memory limit in action. However, I had to leave my script running, since, as much as I mostly use Chrome, system cache consumes a lot of RAM too.



    My steps:



    1- Used this script from: Limit memory usage for a single Linux process



    #!/bin/sh

    # This script uses commands from the cgroup-tools package. The cgroup-tools commands access the cgroup filesystem directly which is against the (new-ish) kernel's requirement that cgroups are managed by a single entity (which usually will be systemd). Additionally there is a v2 cgroup api in development which will probably replace the existing api at some point. So expect this script to break in the future. The correct way forward would be to use systemd's apis to create the cgroups, but afaik systemd currently (feb 2018) only exposes dbus apis for which there are no command line tools yet, and I didn't feel like writing those.

    # strict mode: error if commands fail or if unset variables are used
    set -eu

    if [ "$#" -lt 2 ]
    then
    echo Usage: `basename $0` "<limit> <command>..."
    echo or: `basename $0` "<memlimit> -s <swaplimit> <command>..."
    exit 1
    fi

    cgname="limitmem_$$"

    # parse command line args and find limits

    limit="$1"
    swaplimit="$limit"
    shift

    if [ "$1" = "-s" ]
    then
    shift
    swaplimit="$1"
    shift
    fi

    if [ "$1" = -- ]
    then
    shift
    fi

    if [ "$limit" = "$swaplimit" ]
    then
    memsw=0
    echo "limiting memory to $limit (cgroup $cgname) for command $@" >&2
    else
    memsw=1
    echo "limiting memory to $limit and total virtual memory to $swaplimit (cgroup $cgname) for command $@" >&2
    fi

    # create cgroup
    sudo cgcreate -g "memory:$cgname"
    sudo cgset -r memory.limit_in_bytes="$limit" "$cgname"
    bytes_limit=`cgget -g "memory:$cgname" | grep memory.limit_in_bytes | cut -d -f2`

    # try also limiting swap usage, but this fails if the system has no swap
    if sudo cgset -r memory.memsw.limit_in_bytes="$swaplimit" "$cgname"
    then
    bytes_swap_limit=`cgget -g "memory:$cgname" | grep memory.memsw.limit_in_bytes | cut -d -f2`
    else
    echo "failed to limit swap"
    memsw=0
    fi


    2- Named it as "limitmem" and copied to /usr/bin/ so I could call it from terminal just with limitmem. Now I can open a process limiting the memory usage to, for example, 800MB using this syntax:limitmem 800M command



    In my case: limitmem 1000M google-chrome --password-store=basic --aggressive-cache-discard --aggressive-tab-discard






    share|improve this answer



























      up vote
      0
      down vote



      accepted










      The solution that "fra-san" gave at the comments here fitted perfectly. Using "cgroup-tools" package I was able to limit Chrome memory usage successfully. I tested it opening dozens of tabs at the same time and I could see the memory limit in action. However, I had to leave my script running, since, as much as I mostly use Chrome, system cache consumes a lot of RAM too.



      My steps:



      1- Used this script from: Limit memory usage for a single Linux process



      #!/bin/sh

      # This script uses commands from the cgroup-tools package. The cgroup-tools commands access the cgroup filesystem directly which is against the (new-ish) kernel's requirement that cgroups are managed by a single entity (which usually will be systemd). Additionally there is a v2 cgroup api in development which will probably replace the existing api at some point. So expect this script to break in the future. The correct way forward would be to use systemd's apis to create the cgroups, but afaik systemd currently (feb 2018) only exposes dbus apis for which there are no command line tools yet, and I didn't feel like writing those.

      # strict mode: error if commands fail or if unset variables are used
      set -eu

      if [ "$#" -lt 2 ]
      then
      echo Usage: `basename $0` "<limit> <command>..."
      echo or: `basename $0` "<memlimit> -s <swaplimit> <command>..."
      exit 1
      fi

      cgname="limitmem_$$"

      # parse command line args and find limits

      limit="$1"
      swaplimit="$limit"
      shift

      if [ "$1" = "-s" ]
      then
      shift
      swaplimit="$1"
      shift
      fi

      if [ "$1" = -- ]
      then
      shift
      fi

      if [ "$limit" = "$swaplimit" ]
      then
      memsw=0
      echo "limiting memory to $limit (cgroup $cgname) for command $@" >&2
      else
      memsw=1
      echo "limiting memory to $limit and total virtual memory to $swaplimit (cgroup $cgname) for command $@" >&2
      fi

      # create cgroup
      sudo cgcreate -g "memory:$cgname"
      sudo cgset -r memory.limit_in_bytes="$limit" "$cgname"
      bytes_limit=`cgget -g "memory:$cgname" | grep memory.limit_in_bytes | cut -d -f2`

      # try also limiting swap usage, but this fails if the system has no swap
      if sudo cgset -r memory.memsw.limit_in_bytes="$swaplimit" "$cgname"
      then
      bytes_swap_limit=`cgget -g "memory:$cgname" | grep memory.memsw.limit_in_bytes | cut -d -f2`
      else
      echo "failed to limit swap"
      memsw=0
      fi


      2- Named it as "limitmem" and copied to /usr/bin/ so I could call it from terminal just with limitmem. Now I can open a process limiting the memory usage to, for example, 800MB using this syntax:limitmem 800M command



      In my case: limitmem 1000M google-chrome --password-store=basic --aggressive-cache-discard --aggressive-tab-discard






      share|improve this answer

























        up vote
        0
        down vote



        accepted







        up vote
        0
        down vote



        accepted






        The solution that "fra-san" gave at the comments here fitted perfectly. Using "cgroup-tools" package I was able to limit Chrome memory usage successfully. I tested it opening dozens of tabs at the same time and I could see the memory limit in action. However, I had to leave my script running, since, as much as I mostly use Chrome, system cache consumes a lot of RAM too.



        My steps:



        1- Used this script from: Limit memory usage for a single Linux process



        #!/bin/sh

        # This script uses commands from the cgroup-tools package. The cgroup-tools commands access the cgroup filesystem directly which is against the (new-ish) kernel's requirement that cgroups are managed by a single entity (which usually will be systemd). Additionally there is a v2 cgroup api in development which will probably replace the existing api at some point. So expect this script to break in the future. The correct way forward would be to use systemd's apis to create the cgroups, but afaik systemd currently (feb 2018) only exposes dbus apis for which there are no command line tools yet, and I didn't feel like writing those.

        # strict mode: error if commands fail or if unset variables are used
        set -eu

        if [ "$#" -lt 2 ]
        then
        echo Usage: `basename $0` "<limit> <command>..."
        echo or: `basename $0` "<memlimit> -s <swaplimit> <command>..."
        exit 1
        fi

        cgname="limitmem_$$"

        # parse command line args and find limits

        limit="$1"
        swaplimit="$limit"
        shift

        if [ "$1" = "-s" ]
        then
        shift
        swaplimit="$1"
        shift
        fi

        if [ "$1" = -- ]
        then
        shift
        fi

        if [ "$limit" = "$swaplimit" ]
        then
        memsw=0
        echo "limiting memory to $limit (cgroup $cgname) for command $@" >&2
        else
        memsw=1
        echo "limiting memory to $limit and total virtual memory to $swaplimit (cgroup $cgname) for command $@" >&2
        fi

        # create cgroup
        sudo cgcreate -g "memory:$cgname"
        sudo cgset -r memory.limit_in_bytes="$limit" "$cgname"
        bytes_limit=`cgget -g "memory:$cgname" | grep memory.limit_in_bytes | cut -d -f2`

        # try also limiting swap usage, but this fails if the system has no swap
        if sudo cgset -r memory.memsw.limit_in_bytes="$swaplimit" "$cgname"
        then
        bytes_swap_limit=`cgget -g "memory:$cgname" | grep memory.memsw.limit_in_bytes | cut -d -f2`
        else
        echo "failed to limit swap"
        memsw=0
        fi


        2- Named it as "limitmem" and copied to /usr/bin/ so I could call it from terminal just with limitmem. Now I can open a process limiting the memory usage to, for example, 800MB using this syntax:limitmem 800M command



        In my case: limitmem 1000M google-chrome --password-store=basic --aggressive-cache-discard --aggressive-tab-discard






        share|improve this answer














        The solution that "fra-san" gave at the comments here fitted perfectly. Using "cgroup-tools" package I was able to limit Chrome memory usage successfully. I tested it opening dozens of tabs at the same time and I could see the memory limit in action. However, I had to leave my script running, since, as much as I mostly use Chrome, system cache consumes a lot of RAM too.



        My steps:



        1- Used this script from: Limit memory usage for a single Linux process



        #!/bin/sh

        # This script uses commands from the cgroup-tools package. The cgroup-tools commands access the cgroup filesystem directly which is against the (new-ish) kernel's requirement that cgroups are managed by a single entity (which usually will be systemd). Additionally there is a v2 cgroup api in development which will probably replace the existing api at some point. So expect this script to break in the future. The correct way forward would be to use systemd's apis to create the cgroups, but afaik systemd currently (feb 2018) only exposes dbus apis for which there are no command line tools yet, and I didn't feel like writing those.

        # strict mode: error if commands fail or if unset variables are used
        set -eu

        if [ "$#" -lt 2 ]
        then
        echo Usage: `basename $0` "<limit> <command>..."
        echo or: `basename $0` "<memlimit> -s <swaplimit> <command>..."
        exit 1
        fi

        cgname="limitmem_$$"

        # parse command line args and find limits

        limit="$1"
        swaplimit="$limit"
        shift

        if [ "$1" = "-s" ]
        then
        shift
        swaplimit="$1"
        shift
        fi

        if [ "$1" = -- ]
        then
        shift
        fi

        if [ "$limit" = "$swaplimit" ]
        then
        memsw=0
        echo "limiting memory to $limit (cgroup $cgname) for command $@" >&2
        else
        memsw=1
        echo "limiting memory to $limit and total virtual memory to $swaplimit (cgroup $cgname) for command $@" >&2
        fi

        # create cgroup
        sudo cgcreate -g "memory:$cgname"
        sudo cgset -r memory.limit_in_bytes="$limit" "$cgname"
        bytes_limit=`cgget -g "memory:$cgname" | grep memory.limit_in_bytes | cut -d -f2`

        # try also limiting swap usage, but this fails if the system has no swap
        if sudo cgset -r memory.memsw.limit_in_bytes="$swaplimit" "$cgname"
        then
        bytes_swap_limit=`cgget -g "memory:$cgname" | grep memory.memsw.limit_in_bytes | cut -d -f2`
        else
        echo "failed to limit swap"
        memsw=0
        fi


        2- Named it as "limitmem" and copied to /usr/bin/ so I could call it from terminal just with limitmem. Now I can open a process limiting the memory usage to, for example, 800MB using this syntax:limitmem 800M command



        In my case: limitmem 1000M google-chrome --password-store=basic --aggressive-cache-discard --aggressive-tab-discard







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Dec 4 at 8:54

























        answered Dec 4 at 8:21









        Lucas Rizzini

        113




        113






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Unix & Linux Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f483898%2fshell-script-to-periodically-free-some-memory-up-with-ubuntu-18-10-livecd-with-o%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Entries order in /etc/network/interfaces

            新発田市

            Grub takes very long (several minutes) to open Menu (in Multi-Boot-System)