曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 5556|回复: 0
打印 上一主题 下一主题

[进程] tcgetpgrp() -- 获取前台进程组ID

[复制链接]

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34397
跳转到指定楼层
楼主
发表于 2012-7-25 11:58:48 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
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 个文件描述符,它们关联着的终端可能是某个虚拟终端。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2025-6-19 06:28 , Processed in 0.061172 second(s), 23 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表