【发布时间】: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文件,因此如果您想执行与它相同的操作,请参阅手册页。不过,这与检查打开的终端并不完全相同。 -
你的程序正在检查它可以打开多少个终端,而不是哪些已经打开。