I worked out the function for the setpgid() when i executing this function the result will be permission denied. then i logged in as a root user that time also this will print the error message as permission denied. then which user can use this function. Can anyone 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);
}
First of all, you really need to check the return value of your function calls before you call perror()
, otherwise you don't know which of your calls that failed - it might not been the most recent call before your perror()
statement that failed. The code should be something like:
if (setpgid(getpid(),pgid) != 0) {
perror("setpgid");
}
If it really is setpgid() that fails, here's what the docs says:
EPERM An attempt was made to move a process into a process group in a different session, or to change the process group ID of one of the children of the calling process and the child was in a different session, or to change the process group ID of a session leader (setpgid(), setpgrp()).
So it sounds like you are hitting this first case described since your child process calls setsid()
.
The glibc docs about job control has a bit of reading material on this subject.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With