ttyname.inc 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. {
  2. This file is part of the Free Pascal run time library.
  3. Copyright (c) 1999-2000 by Peter Vreman
  4. member of the Free Pascal development team.
  5. See the file COPYING.FPC, included in this distribution,
  6. for details about the copyright.
  7. A generic implementation of ttyname functionality.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  11. **********************************************************************}
  12. function TTYName(Handle:cint):string;
  13. {
  14. Return the name of the current tty described by handle f.
  15. returns empty string in case of an error.
  16. }
  17. var
  18. mydev : dev_t;
  19. myino : ino_t;
  20. st : stat;
  21. function mysearch(n:string): boolean;
  22. {searches recursively for the device in the directory given by n,
  23. returns true if found and sets the name of the device in ttyname}
  24. var dirstream : pdir;
  25. d : pdirent;
  26. name : string;
  27. st : stat;
  28. begin
  29. dirstream:=fpopendir(n);
  30. if (dirstream=nil) then
  31. exit(false);
  32. d:=fpReaddir(dirstream^);
  33. while (d<>nil) do
  34. begin
  35. name:=n+'/'+strpas(@(d^.d_name));
  36. // fpstat(name,st);
  37. if fpstat(name,st)=0 then
  38. begin
  39. if (fpS_ISDIR(st.st_mode)) and { if it is a directory }
  40. (strpas(@(d^.d_name))<>'.') and { but not ., .. and fd subdirs }
  41. (strpas(@(d^.d_name))<>'..') and
  42. (strpas(@(d^.d_name))<>'') and
  43. (strpas(@(d^.d_name))<>'fd') then
  44. begin {we found a directory, search inside it}
  45. if mysearch(name) then
  46. begin {the device is here}
  47. fpclosedir(dirstream^); {then don't continue searching}
  48. mysearch:=true;
  49. exit;
  50. end;
  51. end
  52. else if (ino_t(d^.d_fileno)=myino) and (st.st_dev=mydev) then
  53. begin
  54. fpclosedir(dirstream^);
  55. ttyname:=name;
  56. mysearch:=true;
  57. exit;
  58. end;
  59. end;
  60. d:=fpReaddir(dirstream^);
  61. end;
  62. fpclosedir(dirstream^);
  63. mysearch:=false;
  64. end;
  65. begin
  66. TTYName:='';
  67. if (fpfstat(handle,st)=-1) or (isatty (handle)<>1) then
  68. exit;
  69. mydev:=st.st_dev;
  70. myino:=st.st_ino;
  71. mysearch('/dev');
  72. end;
  73. function TTYName(var F:Text):string;
  74. {
  75. Idem as previous, only now for text variables;
  76. }
  77. begin
  78. TTYName:=TTYName(textrec(f).handle);
  79. end;