题目:编写一小段程序,要求调用fork并使子进程建立一个新的会话。验证子进程变成进程组组长并不再具有控制终端。
答案(仅供参考)
#include
#include
int main()
{
pid_t pid;
if((pid = fork()) < 0){
err_sys("fork error");
}else if(pid == 0){
int result = open("/dev/tty",0);
if(result < 0){
printf("In child process can't open /dev/tty before setsid()\n");
}else{
printf("In child process can open /dev/tty before setsid()\n");
}
printf("In child process,before setsid() the process group id is %d and process id is %d \n",getpgrp(),getpid());
setsid();
printf("In child process,before setsid() the process group id is %d and process id is %d \n",getpgrp(),getpid());
result = open("/dev/tty",0);
if(result < 0){
printf("In child process can't open /dev/tty after setsid()\n");
}
}else{
printf("In parent process,process group id is %d , process id is %d \n",getpgrp(),getpid());
}
return 0;
}
答案(仅供参考)
#include
#include
int main()
{
pid_t pid;
if((pid = fork()) < 0){
err_sys("fork error");
}else if(pid == 0){
int result = open("/dev/tty",0);
if(result < 0){
printf("In child process can't open /dev/tty before setsid()\n");
}else{
printf("In child process can open /dev/tty before setsid()\n");
}
printf("In child process,before setsid() the process group id is %d and process id is %d \n",getpgrp(),getpid());
setsid();
printf("In child process,before setsid() the process group id is %d and process id is %d \n",getpgrp(),getpid());
result = open("/dev/tty",0);
if(result < 0){
printf("In child process can't open /dev/tty after setsid()\n");
}
}else{
printf("In parent process,process group id is %d , process id is %d \n",getpgrp(),getpid());
}
return 0;
}
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/7232789/viewspace-687225/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/7232789/viewspace-687225/