• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 428
  • Last Modified:

Detect background processing

I.E. Within my perl script, if I'm running as a foreground
process then I want to give the user the option to alter the setup. If the script is run as a background process then it runs with defaults set.

I've had numerous suggestions from checking the $SHELL env var to the -t test operator to system("tty -s") and checking $? var.  These can all distingush between running as a foreground process or as a cron/at process but they don't work for background process spawn via nohup or & from a foreground shell process. i.e. they inherit from the parent shell.

Any ideas????
0
brent.webster
Asked:
brent.webster
1 Solution
 
gareeCommented:
Here's a small C code which does what you want.  It can be
converted to Perl.  The ioctl may be tricky in Perl, I haven't
looked into it.

/* This program checks to see if the process is running in the background.
   The process is in the background if its standard output is not directed
   to a tty, or if the terminal output device's process group is not the same
   as the process's process group.

   Usage:  isbackground [-v]

            -v  Report findings
   
   Return value:  0  process is in background
                  1  process is in foreground
                  2  error  */

#include <sys/ioctl.h>

main(int argc, char **argv)
{
   int  tty;
   int  pgrp, tpgrp;
   int  vflag = 0;

   if (argc > 1)
   {
      vflag = (strcmp(argv[1], "-v") == 0);
   }

   if (isatty(1))
   {
      if (ioctl(1, TIOCGPGRP, &tpgrp))
      {
         perror("ioctl");
         exit(2);
      }

      pgrp = getpgrp();

      if (pgrp == tpgrp)
      {
         if (vflag)  printf("Process running in foreground.\n");
         exit(1);
      }
      else
      {
         if (vflag)  printf("Process running in background.\n");
         exit(0);
      }
   }

   if (vflag)  printf("Process running in background.\n");
   exit(0);
}

0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now