Which user can use the setpgid () function?

I developed a function for setpgid (), when I execute this function, the result will be rejected. then I logged in as the root user, and this time will also display an error message with permission. which user can use this function. Can someone explain to me?

#include<stdio.h> #include<unistd.h> #include<stdlib.h> main() { printf("parent pid=%d\tpgid=%d\n",getpid(),getpgid(getpid())); pid_t pid,pgid; pgid=getpgid(getpid()); if((pid=fork())==0) { printf("befor sessionchild pid=%d\tpgid=%d\n",getpid(),getpgid(getpid())); sleep(5); pid_t p; printf("child pid=%d\tpgid=%d\n",getpid(),getpgid(getpid())); if((p=fork())==0){ sleep(2); setsid(); printf("child2 pid=%d\tpgid=%d\n",getpid(),getpgid(getpid())); setpgid(getpid(),pgid); perror("Error"); printf("after setting group id child2 pid=%d\tpgid=%d\n",getpid(),getpgid(getpid())); } wait(0); exit(0); } exit(0); } 
+5
source share
2 answers

First of all, you need to check the return value of your function calls before calling perror() , otherwise you do not know which of your calls failed - this may not be the last call before your perror() that failed. The code should look something like this:

 if (setpgid(getpid(),pgid) != 0) { perror("setpgid"); } 

If this is really a setpgid () error, then what docs says:

EPERM An attempt was made to move a process to a process group in another session or change the process group identifier of one of the children of the calling process and the child was in another session or change the process leader identifier of the session leader (setpgid (), setpgrp ()).

So it looks like you are falling into this first case described, since your child process calls setsid() .

The glibc job management docs have some reading material on this subject.

+2
source

This is not how you should handle error handling.

Check the return value of each API request, look for errors.

If (and only if) an error occurs, then you should check errno and use perror .

0
source

Source: https://habr.com/ru/post/1209234/


All Articles