【问题标题】:How to check which terminals are open using c如何使用c检查哪些终端是打开的
【发布时间】:2016-04-25 03:31:34
【问题描述】:

我正在尝试使用 C 检查打开了哪些终端。当我在终端中键入“w”时,它显示只有 4 个终端是打开的(实际上是我打开了多少个终端)。但是,当我运行此代码时,它告诉我大约有 20 个打开。我该如何解决这个问题?

#include <stdlib.h>
#include <stdio.h> 
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>
#include <time.h>


const char pts[] = "/dev/pts/";
int s1=0;

FILE *fp = NULL;
char *terminal[4];
char* check;

int main(int argc, char *argv[]){

int i;
char strDev[100]; 

for(i=0; i<100; i++){
  sprintf(strDev, "%s%d", pts, i);
  printf("Opening %s...\n", strDev); fflush(stdout);

  if((fp = fopen(strDev, "w")) == NULL) ;
  else{

  printf("\tOpened %s\n", strDev); fflush(stdout);

    terminal[s1] = strDev;
    s1++;
  }
}
return 0;
}

【问题讨论】:

  • 你不能用便携式 C 来做到这一点;该标准没有为它提供任何手段。它需要以某种特定于系统的方式完成,因此您至少需要指定您的操作系统。
  • 作为记录,w 命令使用utmp 文件,因此如果您想执行与它相同的操作,请参阅手册页。不过,这与检查打开的终端并不完全相同。
  • 你的程序正在检查它可以打开多少个终端,而不是哪些已经打开。

标签: c terminal


【解决方案1】:

运行w 是相当可移植的。但只需要计数,而不需要标题。标题的第一行通常是一个状态行,给出了实际的用户数量(但在 C 中难以解析),标题的其余行显示列名,从第一列开始. w 或其格式没有标准。 POSIX 确实描述了who,但避免描述它使用的格式。所以,对于w

#include <stdio.h>
int
main(void)
{
    int result = 0;
    FILE *fp;
    if ((fp = popen("w", "r")) != 0) {
        int lineno = 0;
        char *buffer = 0;
        size_t size = 0;
        int head = 0;
        while (getline(&buffer, &size, fp) > 0) {
            if (lineno++ == 0) {
                head = (*buffer != ' ') ? 2 : 1;
            } else if (head++ > 1) {
                ++result;
            }
        }
        pclose(fp);
    }
    printf("%d terminals are open\n", result);
    return 0;
}

如果您想知道哪些终端正在使用,方法是使用标题中的列信息并从以下行中选择文本。在没有适用标准的情况下,列的宽度(和顺序)可能因系统而异,因此任何使用特定偏移量和字符串长度的解决方案都会有缺陷。

但是,要显示可用(未使用)终端的列表,您需要自己做,因为在某些系统上,相应的特殊设备会受到保护,因此普通(非特权)程序无法打开它们,只能测试它们存在。

【讨论】:

    【解决方案2】:

    为什么不使用system 命令来完成您正在使用的w 命令:

    #include <stdlib.h>
    #include <stdio.h>
    
    int main(int argc, char *argv[]) {
    
        char command[128];
        snprintf(command, sizeof(command), "w");
        system(command);
    
    return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多