title: Using bash and watch to monitor qemu-kvm
body: <p>I'm trying to monitor some <code>qemu-kvm</code> processes using a bash script and <code>watch</code> to show several details like memory/cpu use, resources, ports,etc. Everything is going great until I try to get the IMG file that qemu-kvm is using.</p>
  
  <p>Initially I thought I could get that information from the running process cmd:</p>
  
  <pre><code>ps -p PID -o cmd | tail -1
  qemu-kvm -name TEST -drive file=/img/test.qcow2,if=ide,media=disk,cache=none -daemonize
  </code></pre>
  
  <p>So after plenty of tests I have wrote this little script just to synthesise the problem:</p>
  
  <pre><code>#!/bin/bash
  lsof -p PID | grep '/img/' | awk {'print $9'}
  </code></pre>
  
  <p>The output of this script looks totally fine when I execute it from the command line:</p>
  
  <pre><code>bash testscript
  /img/test.qcow2
  </code></pre>
  
  <p>The problem comes when I try to run the script along with watch:</p>
  
  <p><code>watch -n1 "bash test-script"</code> or <code>watch -n1 ./test-script</code></p>
  
  <p>The output is just empty... </p>
  
  <p>Why don't I get any results? I'd be really glad if somebody can help me understanding this.</p>
  
  <p>EDIT: I have found an alternative solution. I am now getting the information from parsing the procfs with some arrays to find the IMG info:</p>
  
  <pre><code>OIFS=$IFS;
  IFS='-';  
  Array=($(cat /proc/PID/cmdline))
      for ((i=0; i&lt;${#Array[@]}; ++i))
          do
          if [[ "${Array[$i]}" == *drive* ]]; then
              image=${Array[$i]}
              echo $image
          fi
      done
  IFS=$OIFS;
  </code></pre>
  
  <p>This works fine combined with <code>watch</code>, but I would still like to know what's the problem with the other method. Is <code>lsof</code> limited somehow??</p>