user2050516
user2050516

Reputation: 760

Linux change pgrp (process group) during c program execution

C Linux change pgrp (process group) during program execution

Is there a piece of working C code to change your own process group during program execution. Maybe someone can make the testprogram work below.

Bash verification:

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

C test program:

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

Upvotes: 2

Views: 2194

Answers (1)

awatan
awatan

Reputation: 1210

From man pages of setsid.

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

setsid() creates a new session if the calling process is not a process group leader. The calling process is the leader of the new session, the process group leader of the new process group, and has no controlling terminal.

or you can changed your process's group by setpgid() system call. For man's pages of setpgid http://man7.org/linux/man-pages/man2/setpgid.2.html

setpgid() sets the PGID of the process specified by pid to pgid. If pid is zero, then the process ID of the calling process is used. If pgid is zero, then the PGID of the process specified by pid is made the same as its process ID.

but it is mandatory that both process groups belong to the same session i.e. the group from you moving from and the group you moving to. Here is an example of a code which changes process group with out using setsid() and 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;
}

Upvotes: 4

Related Questions