曲径通幽论坛

标题: tcgetpgrp() -- 获取前台进程组ID [打印本页]

作者: beyes    时间: 2012-7-25 11:58
标题: tcgetpgrp() -- 获取前台进程组ID
tcgetpgrp() 函数原型如下:
[C++] 纯文本查看 复制代码
#include <unistd.h>
pid_t tcgetpgrp(int fd);

该函数用来返回前台进程组 ID 。一般情况下,大多数应用程序不会用到此函数,它往往被 shell 这样的程序所使用。对于前台进程组和后台进程组,需要了解的是,在任何某个时刻只有一个前台进程组,而后台进程组可有多个。

当从标准输入里读取数据,或者要将终端信号(如按下 Ctrl + C) 时,设备驱动程序需要将这些信息传递到前台进程组,此时就需要获得前台进程组 ID ;该前台进程组与在 fd 上打开的终端相关联。

测试代码:
[C++] 纯文本查看 复制代码
#include <sys/types.h>
#include <termios.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

main()
{
   pid_t stdin_PGID, stdout_PGID, stderr_PGID;

      /* Get the PGIDs for stdin, stdout, and stderr.  */
   stdin_PGID = tcgetpgrp(STDIN_FILENO);
   if (stdin_PGID == -1) {
      printf("Could not get PGID for stdin.n");
      return(EXIT_FAILURE);
   }
   stdout_PGID = tcgetpgrp(STDOUT_FILENO);
   if (stdout_PGID == -1) {
      printf("Could not get PGID for stdout.n");
      return(EXIT_FAILURE);
   }
   stderr_PGID = tcgetpgrp(STDERR_FILENO);
   if (stderr_PGID == -1) {
      printf("Could not get PGID for stderr.n");
      return(EXIT_FAILURE);
   }

   printf("The PGID for stdin is %d\n", stdin_PGID);
   printf("The PGID for stdout is %d\n", stdout_PGID);
   printf("The PGID for stderr is %d\n", stderr_PGID);

   printf("This process PID is %d\n", getpid());

   return(EXIT_SUCCESS);
}

运行输出:
$ ./tcgetpgrp
The PGID for stdin is 2324
The PGID for stdout is 2324
The PGID for stderr is 2324
This process PID is 2324
由输出可见,如果只是运行该程序,那么该程序会建立一个进程组,而它本身就是这个进程组的组长,因此该进程组的组 ID 和 这个程序本身的 PID 是一样的。此外,程序中用到的 STDIN, STDOUT, STDERR 这 3 个文件描述符,它们关联着的终端可能是某个虚拟终端。




欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2