Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Perl fork pid Not Correcto for Xterm Spawn

by rehmanz (Novice)
on Jul 07, 2010 at 23:58 UTC ( [id://848579]=perlquestion: print w/replies, xml ) Need Help??

rehmanz has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to spawn an xterm window that does a "tail -f" to a summary log file. However the pid is not the correct one! When my script tries to kill the window, the $pid does not has the right process Id. Can someone please help? I have attached my code! Thanks in advance PerlMonks!

#!/usr/bin/perl my $fname = "/tmp/help.txt"; system("echo help me > $fname"); my $pid = fork(); if ($pid eq 0) { sleep (1); system ("xterm -T hello -e tail -f $fname &"); exit(-1); } print "This is not the correct pid: $pid \n"; sleep(5); print "After some point in time, I want to kill $pid! \n"); system ("kill -9 $pid"); print "$pid is incorrect!\n";

Replies are listed 'Best First'.
Re: Perl fork pid Not Correcto for Xterm Spawn
by ikegami (Patriarch) on Jul 08, 2010 at 00:09 UTC
    1. Parent creates a forked copy and sleeps for 5 seconds
    2. The forked copy sleeps for a second.
    3. The forked copy launches a shell.
    4. The shell executes xterm in the background and exits.
    5. The forked copy exits.
    6. The sleep ends
    7. You try to kill a process that exited almost 4 seconds earlier.

    You want the shell to stick around until the xterm exits. Do so by removing the "&".

    Since we don't need to keep the forked copy around since at all it does is exit (with a wrong code), use exec instead of system.

    #!/usr/bin/perl my $fname = "/tmp/help.txt"; system("echo help me > $fname"); my $pid = fork(); if ($pid == 0) { exec("xterm -T hello -e tail -f $fname"); exit($! || 255); } ...

    Even better: Avoid the shell and use a safer interface.

    #!/usr/bin/perl ... my $pid = fork(); if ($pid == 0) { exec('xterm', '-T', 'hello', '-e', 'tail', '-f', $fname); exit($! || 255); } ...

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://848579]
Approved by ikegami
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (2)
As of 2024-04-26 05:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found