c - 将进程置于前台

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

但它不起作用。有人可以帮我解决这个问题吗? 谢谢。

最佳答案

您可以通过调用 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/

相关文章:

C:我无法让这个示例税收计划发挥作用

c - 无效长选项的段错误

linux - Linux 中因版本变更而出现的符号

linux - 解释 UNIX 中不同的 EXIT 命令

c - 如何在 Windows 中结束线程

c - 非常奇怪的数组声明问题 - C

c - 创建 tun 设备时出错(参数无效)

c - 使用 BNF 语法将 c 变量的英文描述转换为 c 风格的变量声明

regex - 在 awk 中捕获双引号之间的单词

c - 为什么 execvp 或 exec* 系列函数之后的任何内容都不会被执行?