将流程带到前台

时间:2012-03-07 13:11:13

标签: c linux process

我有一个后台进程执行的进程(读取和写入终端类型)。我可以用ps看到它。 试图将它带到前台,这就是我的尝试:

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;
}

虽然不行。有人可以帮我吗? 感谢。

2 个答案:

答案 0 :(得分:2)

你可以通过调用shell命令fg并将其传递给pid(建议)来以“软”方式完成。

如果你想编码,这就是将fg / bg编码成bash的方式(不要不这样做):

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);
    }
}

答案 1 :(得分:0)

当您有一个处于后台或暂停的进程时,您可以将其移动到前台 fg命令。默认情况下,最近暂停或移动到后台的进程移动到 前景。您还可以指定使用哪个pid使其成为前景。