c - Linux在c程序执行过程中更改pgrp(进程组)

标签 c linux process grep

C Linux 在程序执行期间更改 pgrp(进程组)

是否有一段有效的 C 代码可以在程序执行期间更改您自己的进程组。 也许有人可以让下面的测试程序工作。

Bash 验证:

# ps -opid,pgrp,cmd | grep <pid>

C测试程序:

#include<stdio.h>

int main(int argc, char *argv[]) {

  pid_t mypid = getpid();
  printf ("issue: ps -opid,pgrp,cmd | grep %d\n", (int) mypid);

  printf ("will change my pgrp in 10 sec\n");
  sleep  (10);

  // missing here is the "magic" statment to change current process group

  printf ("issue: ps -opid,pgrp,cmd | grep %d\n", (int) pid);

  sleep (1000);
}

最佳答案

来自setsid 的手册页。

http://linux.die.net/man/2/setsid

如果调用进程不是进程组领导者,setsid() 将创建一个新 session 。调用进程是新 session 的领导者、新进程组的进程组领导者,并且没有控制终端。

或者您可以通过 setpgid() 系统调用更改进程的组。对于 setpgid 的手册页 http://man7.org/linux/man-pages/man2/setpgid.2.html

setpgid() 将 pid 指定的进程的 PGID 设置为 pgid。如果 pid 为零,则使用调用进程的进程 ID。如果 pgid 为零,则 pid 指定的进程的 PGID 与其进程 ID 相同。

但两个进程组必须属于同一 session ,即您从中移出的组和您移至的组。以下是不使用setsid()和fork()来更改进程组的代码示例:

int main()
{
  pid_t ppgid = 0;
  pid_t mypid = getpid();
  pid_t ppid  = getppid();
  printf("My pid is %d and my pgid is %d\n", getpid(), getpgid(mypid));
  ppgid = getpgid(ppid);
  printf("My parent's pid is %d and his pgid is %d\n", ppid, ppgid);  

  setpgid(mypid, ppgid);  

  printf("Now my pgid is changed to my parent's pgid(%d)\n", getpgid(mypid));

  return 0;
}

关于c - Linux在c程序执行过程中更改pgrp(进程组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26430771/

相关文章:

linux - Collectd-用户 :plugin How to Use

linux - 如何删除 DNS、bind9 中的查询 "NULL"和 "WKS"?

delphi - Delphi如何获取其他进程的信息?

c++ - Windows 上的线程

c - poll如何处理关闭的管道

c - 如何防止 C 中的段错误(当采用错误类型的参数时)

c - 如何在 C 中将 char 分配给 char*?

c++ - 将boost_chrono_FOUND设置为FALSE,因此 “boost_chrono”软件包被视为未找到

c - 生成唯一随机数数组

operating-system - 如何找出进程在 Solaris 上使用的线程数?