/*Program:
* APUE习题9.2
* History:
* 2021/1/21 Chen Ying-jun First release
* */
#include<apue.h>
#include<iostream>
#include<my_error.h>
#include<unistd.h>
#include<fcntl.h>
using namespace std;
int main(){
pid_t pid,pgrp;
if((pid=fork())<0)
err_sys("fork error");
else if(pid==0){//child
int sessionPid;
//build session
if((sessionPid=setsid())<0)
err_sys("setsid error");
cout<<"process id of session="<<sessionPid<<endl;
//验证是否有控制终端
if(open("/dev/tty",O_RDONLY)<0)
cout<<"can't open /dev/tty"<<endl;
else
cout<<"can open /dev/tty"<<endl;
}else{
//使子进程先运行,以建立会话
sleep(3);
if((pgrp=getpgid(pid))<0)
err_sys("setid error");
cout<<"child process id="<<pid<<endl;
cout<<"group id of child process="<<pgrp<<endl;
}
exit(0);
}
运行结果:
process id of session=3780
can’t open /dev/tty
child process id=3780
group id of child process=3780
子进程id=会话id(即会话首进程id)=子进程所在进程组id。
无法打开/dev/tty,说明该进程组不是前台进程,没有控制终端。
和题目预期相符。