...which is not working as expected.

So what do you expect?  Basically, the approach is fine — except that you got it the wrong way round wrt what is child and parent (if ($pid == 0) {...} is the child).

Here's a slightly modified version which does what I would expect, i.e. have perl.pl (and its children, if any) run under a new process group:

#!/usr/bin/perl use strict; use warnings; my $cmd = qq{nohup ./perl.pl &}; my $pid = fork; die 'fork failed' unless defined $pid; if ($pid) { print STDERR "parent pid=$$ child pid=$pid\n"; wait; my $sid = getppid; system "ps f -s $sid -o pid,ppid,pgrp,sid,cmd"; } else { print STDERR "child pid=$$ \$pid=$pid\n"; setpgrp; exec $cmd or die "Bad exec: $!"; }

With perl.pl being

#!/usr/bin/perl system 'sleep 1';

the output is something like

$ ./813283.pl child pid=31851 $pid=0 parent pid=31850 child pid=31851 PID PPID PGRP SID CMD 18307 18305 18307 18307 bash -rcfile .bashrc 31850 18307 31850 18307 \_ /usr/bin/perl ./813283.pl 31853 31850 31850 18307 \_ ps f -s 18307 -o pid,ppid,pgrp,sid,cmd 31852 1 31851 18307 /usr/bin/perl ./perl.pl 31854 31852 31851 18307 \_ sleep 1

As you can see in the PGRP column, perl.pl and its child process sleep 1 is running under a different process group (31851 in the sample output).


In reply to Re: Run Perl script in perl program with new process group by almut
in thread Run Perl script in perl program with new process group by veshwar

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.