1

So I'm going to preface this by saying that this is for a homework project in my class. I am supposed to determine that the user opened four terminal windows before running the program, and I have to do this by determining if I can open four terminal number buffers from /dev/pts/ as read-only. I then have to save these first four buffers so I can open them again to write to the terminals. I know how to open the files with fopen but my issue is even the terminals that aren't open anymore still show up and are accessible. I know that its pretty frowned upon to ask for homework help but I've been working at this for hours and I don't want it written for me I just want some direction. How can I check that there are four terminals open using the method that I have to use? Also here's my code so maybe one of y'all can see what I'm doing wrong.

#include <stdio.h>
#include <stdlib.h>

#define MAXLINE 100

int main(){
    int i, ptsNum[4], ptsCount = 0;
    FILE *fp;
    char ptsName[20];

    for(i = 0; i < 20; i++){
        // Append the terminal number to the end of the buffer name
        sprintf(ptsName, "/dev/pts/%d", i);
        // Try to open the file
        if((fp = fopen(ptsName, "r")) != NULL){
            // Save the terminal number if the buffer exists
            ptsNum[ptsCount] = i;
            ptsCount++;
            fclose(fp);
        }
    }

return 0;
}
Henry
  • 11
  • 3
  • 1
    You didn't ask any questions. I suppose you need here `inotify` for `/dev/pts` directory. – fghj Apr 22 '16 at 00:27
  • Yeah sorry about that I wasn't really clear. When I run the code above it stores the number for terminals that were opened but aren't anymore. Will that command you posted help with my problem? – Henry Apr 22 '16 at 00:32
  • @Henry -- Please edit your question rather than adding a comment. – Jay Elston Apr 22 '16 at 00:38
  • read http://man7.org/linux/man-pages/man7/inotify.7.html or just type `man inotify` http://stackoverflow.com/questions/13351172/inotify-file-in-c – fghj Apr 22 '16 at 00:41
  • @user1034749 I read both of those but I don't understand how that would help me. The user needs to have the four terminal windows open before running it, so all of the changes to the file system happen before the code is running. – Henry Apr 22 '16 at 00:47
  • 1
    So I just changed `for(i = 0; i < 20; i++){` to `for(i = 1; i < 20; i++){` and after running through gdb it seems that my code finally works, I'm not a smart man. – Henry Apr 22 '16 at 01:02
  • @Henry, check that you traverse 20 terminals but you have space in `ptsNum` only for 4, so in case you try to open the fifth, you'll get into U.B. (probably your program will hang) – Luis Colorado Apr 22 '16 at 13:25

1 Answers1

0

Well, you try to open the terminals, but once you get them counted, you fclose(3) them, so in case you want them open, don't do the last fclose(3) at the end of the loop.

Luis Colorado
  • 10,974
  • 1
  • 16
  • 31