title: How to exit a chroot inside a perl script?
body: <p>While writing a perl script intended to fully automate the setup of virtual machines (Xen pv) I hit a small maybe very simple problem.</p>
  
  <p>Using perl's <a href="http://perldoc.perl.org/functions/chroot.html" rel="nofollow">chroot function</a> I do my things on the guest file system and then I need to get back to my initial real root. How the hell I do that?</p>
  
  <p>Script example:</p>
  
  <pre><code>`mount $disk_image $mount_point`;
  
  chdir($mount_point);
  chroot($mount_point);
  
  #[Do my things...]
  
  #&lt;Exit chroot wanted here&gt;
  
  `umount $mount_point`;
  
  #[Post install things...]
  </code></pre>
  
  <p>I've tried <em>exit;</em> but obviously that exit the whole script.</p>
  
  <p>Searching for a way to exit the chroot I've found a number of scripts who aim to exit an <strong>already</strong> setup chroot (privilege escalation). Since I do the chroot here theses methods do not aplies.</p>
  
  <p>Tried some crazy things like:</p>
  
  <pre><code>opendir REAL_ROOT, "/";
  chdir($mount_point);
  chroot($mount_point);
  chdir(*REAL_ROOT);
  </code></pre>
  
  <p>But no go.</p>
  
  <p><strong>UPDATE</strong>
  Some points to consider:</p>
  
  <ul>
  <li>I can't split the script in multiple files. (Silly reasons, but really, I can't)</li>
  <li>The chrooted part involve using a lot of data gathered earlier by the script (before the chroot), enforcing the need of not lunching another script inside the chroot.</li>
  <li>Using open, system or backticks is not good, I need to run commands and based on the output (not the exit code, the actual output) do other things.</li>
  <li>Steps after the chroot depends on what was done inside the chroot, hence I need to have all the variables I defined or changed while inside, outside.</li>
  <li>Fork is possible, but I don't know a good way to handle correctly the passing of informations from and to the child.</li>
  </ul>