Chinaunix首页 | 论坛 | 博客

分类: LINUX

2008-04-15 21:03:02

二、会话

4

名称:

setsid

功能:

建立一个会话

头文件:

#include

函数原形:

pid_t setsid(void);

参数:

返回值:

若成功则返回进程组ID,若出错则返回-1

 

 

 

 

 

 

 

 

 

会话是一个或多个进程组的集合。进程调用setsid函数建立一个新会话。

如果调用此函数的进程不是一个进程组的组长,则此函数九会创建一个新会话,该进餐变成会话的首进程,然后该进程成为一个新进程组的组长进程,该进程没有控制终端。因为会话首进程是具有唯一进程ID的单个进程,所以可以将会话首进程的进程ID视为会话Id

 

 

5

名称:

getsid

功能:

获得会话首进程的进程id

头文件:

#include

函数原形:

pid_t getsid(pid_t pid);

参数:

pid

返回值:

若成功则返回进程组ID,若出错则返回-1

 

 

 

 

 

 

 

 

#include

#include

 

mian()

{

pid_t pid;

if((pid=fork())==0)

{

    printf(“I’m a child,my id is %d\n”,getpid());

  printf(“My group id is %d\n”,getpgid(0));

    printf(“My father id is %d\n”,getppid());

    printf(“My session id is %d\n”,getsid(0));

}

else

{

    printf(“I’m a father,my id is %d\n”,getpid());

    printf(“My group id is %d\n”,getpgid(0));

    printf(“My father id is %d\n”,getppid());

    printf(“My session id is %d\n”,getsid(0));

}

}

 

#include

#include

 

mian()

{

pid_t pid;

if((pid=fork())==0)

{

    setsid();

    printf(“I’m a child,my id is %d\n”,getpid());

  printf(“My group id is %d\n”,getpgid(0));

    printf(“My father id is %d\n”,getppid());

    printf(“My session id is %d\n”,getsid(0));

}

else

{

    printf(“I’m a father,my id is %d\n”,getpid());

  printf(“My group id is %d\n”,getpgid(0));

    printf(“My father id is %d\n”,getppid());

    printf(“My session id is %d\n”,getsid(0));

}

}

先运行上面的程序,得到的结果为:

I’m a child,my id is 17064.

My group id is 17063

My father id is 17063

My session id is 16619.

I’m a father,my id is 17063.

My group id is 17063

My father id is 16619.

My session id is 16619.

再运行下面的程序。

I’m a child,my id is 17066.

My group id is 17066

My father id is 17065

My session id is 17066.

I’m a father,my id is 17065.

My group id is 17065

My father id is 16619

My session id is 16619.

我们可以看到在子进程没用setsid函数建立一个会话之前,子进程是和父进程在同一会话里的,当子进程用setsid函数建立一个会话,会话的首进程ID就是子进程ID也就是会话ID。

 

6.

名称:

tcgetpgrp/ tcsetpgrp

功能:

获得前台进程组的ID

头文件:

#include

#include

函数原形:

pid_t tcgetpgrp(int filedes);

int tcsetpgrp(int filedes,pid_t pgrpid);

参数:

filedes

返回值:

若成功则返回前台进程组,若出错则返回-1(tcgetpgrp)

若成功则返回0,若出错则返回-1(tcsetpgrp)

 

 

 

 

 

 

 

 

 

 

 

 

函数tcgetpgrp返回前台进程组ID,它与在filedes上打开的终端有关。

如果进程有一个控制终端,则该进程可以调用tcsetpgrp将前台进程组ID设置为pgrpid.它是在同一对话期中的一个进程组的IDfiledes必须引用该对话期的控制终端。

大多数程序并不直接调用这两个函数。它们通常有作业控制shell调用,只有定义了_POSIX_JOB_CONTROL,这两个函数才被定义。

阅读(601) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~