The problem with your second example seems to be that the child process (running the while) still has the slave file descriptor opened. Closing the slave file descriptor it in the child process fixes it for me; I changed return $pty if $child; to:
if ($child) { $pty->close_slave(); return $pty; }
See this note in the IO::Pty documentation:
close_slave()
The slave filehandle will be closed and destroyed. This is necessary in the parent after forking to get rid of the open filehandle, otherwise the parent will not notice if the child exits. Subsequent calls of slave() will return a newly opened slave filehandle.

Also, it's customary to have the child start up a new process and have the parent continue the main flow of execution; your way will work, but isn't the normal way of doing things. And if you're using system(...); exit(0); in your actual program (and not just this sample code), consider using exec instead.

Update: Yup, I misread ph713's code; it forks in a perfectly normal way.


In reply to Re: How do you properly tty-ify a non-tty STDOUT? by sgifford
in thread How do you properly tty-ify a non-tty STDOUT? by ph713

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.