我有一个已由后台进程执行的进程(可读取并写入终端类型)。我可以使用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;
}

它不起作用。有人可以帮我吗?
谢谢。

最佳答案

您可以通过调用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);
    }
}

关于c - 将流程置于前台,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9602153/

10-11 20:54