2

I have a process (which reads and writes to terminal type) that has been exec'd by a background process. I can see it using ps. Trying to bring it to foreground, this is what I attempted:

int main()

{

    FILE* fd = popen("pidof my_program","r");

    // ...
    // Some code to get the pid of my_program as mpid
    //...

    printf("pid of my_program is %d",mpid);
    signal(SIGTTOU, SIG_IGN);
    setpgid(mpid,0); // Set program group id to pid of process
    tcsetpgrp(0,mpid); // Give it terminal stdin access
    tcsetpgrp(1,mpid); // Give it terminal stdout access
    return 0;
}

It isn't working though. Can someone help me on this? Thanks.

Bornfree
  • 868
  • 7
  • 21

2 Answers2

2

You could do it the "soft" way, by calling the shell command fg and pass it the pid (adviced).

If you want to code it, this is how fg/bg is coded into bash (don't don't don't):

static int
fg_bg (list, foreground)
     WORD_LIST *list;
     int foreground;
{
  sigset_t set, oset;
  int job, status, old_async_pid;
  JOB *j;

  BLOCK_CHILD (set, oset);
  job = get_job_spec (list);

  if (INVALID_JOB (job))
    {
      if (job != DUP_JOB)
    sh_badjob (list ? list->word->word : _("current"));

      goto failure;
    }

  j = get_job_by_jid (job);
  /* Or if j->pgrp == shell_pgrp. */
  if (IS_JOBCONTROL (job) == 0)
    {
      builtin_error (_("job %d started without job control"), job + 1);
      goto failure;
    }

  if (foreground == 0)
    {
      old_async_pid = last_asynchronous_pid;
      last_asynchronous_pid = j->pgrp;  /* As per Posix.2 5.4.2 */
    }

  status = start_job (job, foreground);

  if (status >= 0)
    {
    /* win: */
      UNBLOCK_CHILD (oset);
      return (foreground ? status : EXECUTION_SUCCESS);
    }
  else
    {
      if (foreground == 0)
    last_asynchronous_pid = old_async_pid;

    failure:
      UNBLOCK_CHILD (oset);
      return (EXECUTION_FAILURE);
    }
}
vulkanino
  • 9,074
  • 7
  • 44
  • 71
  • But I'm running this on embedded linux machine where I only have busybox binaries and I don't have either fg, bg or jobs available. How do I do it then? – Bornfree Mar 12 '12 at 07:04
0

When you have a process that is in the background or suspended, you can move it to the foreground with the fg command. By default, the process most recently suspended or moved to the background moves to the foreground. You can also specify which pid it is using to make it foreground.

Shash
  • 4,160
  • 8
  • 43
  • 67
  • But I'm running this on embedded linux machine where I only have busybox binaries and I don't have either fg, bg or jobs available. How do I do it then? – Bornfree Mar 12 '12 at 07:05