-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
SimplePipes.pas
855 lines (724 loc) · 32.3 KB
/
SimplePipes.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
{-------------------------------------------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
-------------------------------------------------------------------------------}
{===============================================================================
Simple pipes
This library provides wrappers for pipes available in different operating
systems (currently only Windows and Linux systems are supported). To keep
things simple, all pipes provided here are unidirectional (no duplex pipes)
and blocking.
To properly use the pipes, first create a pipe server using a Create*
constructor and then create a pipe client using Connect* constructor (note
that the ends can be in different threads and even processes). The ends
must be in opposite access mode (read-write), so if you create write
server, the client must be in read mode, and vice-versa. Failure to do so
will result in undefined behaviour and unexpected results.
Three types of pipes are currently implemented - anonymous pipe (TPipe or
TAnonymousPipe), shared pipe (TSharedPipe) and named pipe (TNamedPipe).
Anonymous pipes do no have name. To connect to an anonymous server, you
have to provide binary connection data to the Connect* constructor. These
data are exposed on the server via ConnectionData property. How to pass
them to the client thread or process is up to you (global memory, shared
memory, messages, ...).
Shared pipes are based on anonymous pipes, but they have a global name
(case-insensitive). When you create a server, it stores connection data
to a shared memory under its own name. When you want to connect to it,
pass the same name to client constructor and it will get the connection
data automatically from this shared memory - so you don't have to manage
any IPC or other means of data sharing.
Named pipes works similarly to shared pipes (on the outside, not
internally), but they are managed by the operating system. Simply pass
the same name to both server and client and you are golden.
NOTE - names of named pipes are case-insensitive on all systems.
WARNING - named pipes will not exit their constructors (both server and
client) - ie. will block - until the other end is connected.
This can lead to a deadlocks (especially if you try to create
both ends in the same thread), so be careful.
Version 1.1.2 (2024-05-03)
Last change 2024-09-09
©2022-2024 František Milt
Contacts:
František Milt: frantisek.milt@gmail.com
Support:
If you find this code useful, please consider supporting its author(s) by
making a small donation using the following link(s):
https://www.paypal.me/FMilt
Changelog:
For detailed changelog and history please refer to this git repository:
github.com/TheLazyTomcat/Lib.SimplePipes
Dependencies:
AuxClasses - github.com/TheLazyTomcat/Lib.AuxClasses
* AuxExceptions - github.com/TheLazyTomcat/Lib.AuxExceptions
AuxTypes - github.com/TheLazyTomcat/Lib.AuxTypes
InterlockedOps - github.com/TheLazyTomcat/Lib.InterlockedOps
NamedSharedItems - github.com/TheLazyTomcat/Lib.NamedSharedItems
* StrRect - github.com/TheLazyTomcat/Lib.StrRect
Library AuxExceptions is required only when rebasing local exception classes
(see symbol SimplePipes_UseAuxExceptions for details).
Library StrRect is required only when compiling for Windows OS.
Libraries AuxExceptions and StrRect might also be required as an indirect
dependencies.
Indirect dependencies:
BasicUIM - github.com/TheLazyTomcat/Lib.BasicUIM
BitOps - github.com/TheLazyTomcat/Lib.BitOps
HashBase - github.com/TheLazyTomcat/Lib.HashBase
SHA1 - github.com/TheLazyTomcat/Lib.SHA1
SharedMemoryStream - github.com/TheLazyTomcat/Lib.SharedMemoryStream
SimpleCPUID - github.com/TheLazyTomcat/Lib.SimpleCPUID
SimpleFutex - github.com/TheLazyTomcat/Lib.SimpleFutex
StaticMemoryStream - github.com/TheLazyTomcat/Lib.StaticMemoryStream
UInt64Utils - github.com/TheLazyTomcat/Lib.UInt64Utils
WinFileInfo - github.com/TheLazyTomcat/Lib.WinFileInfo
===============================================================================}
unit SimplePipes;
{
SimplePipes_UseAuxExceptions
If you want library-specific exceptions to be based on more advanced classes
provided by AuxExceptions library instead of basic Exception class, and don't
want to or cannot change code in this unit, you can define global symbol
SimplePipes_UseAuxExceptions to achieve this.
}
{$IF Defined(SimplePipes_UseAuxExceptions)}
{$DEFINE UseAuxExceptions}
{$IFEND}
//------------------------------------------------------------------------------
{$IF Defined(WINDOWS) or Defined(MSWINDOWS)}
{$DEFINE Windows}
{$ELSEIF Defined(LINUX) and Defined(FPC)}
{$DEFINE Linux}
{$ELSE}
{$MESSAGE FATAL 'Unsupported operating system.'}
{$IFEND}
{$IFDEF FPC}
{$MODE ObjFPC}
{$MODESWITCH DuplicateLocals+}
{$ENDIF}
{$H+}
interface
uses
SysUtils,{$IFNDEF Windows} baseunix,{$ENDIF}
AuxTypes, AuxClasses, NamedSharedItems
{$IFDEF UseAuxExceptions}, AuxExceptions{$ENDIF};
{===============================================================================
Library-specific exceptions
===============================================================================}
type
ESPException = class({$IFDEF UseAuxExceptions}EAEGeneralException{$ELSE}Exception{$ENDIF});
ESPSystemError = class(ESPException);
ESPNoServer = class(ESPException);
ESPHandleDupError = class(ESPException);
ESPInvalidMode = class(ESPException);
ESPPeekError = class(ESPException);
ESPReadError = class(ESPException);
ESPWriteError = class(ESPException);
{===============================================================================
--------------------------------------------------------------------------------
TPipeBase
--------------------------------------------------------------------------------
===============================================================================}
type
TSPEndpointMode = (emRead,emWrite);
TSPEndpointHandle = {$IFDEF Windows}THandle{$ELSE}cInt{$ENDIF};
{===============================================================================
TPipeBase - class declaration
===============================================================================}
type
TPipeBase = class(TCustomObject)
protected
fISServer: Boolean;
fEndpointMode: TSPEndpointMode;
fReadHandle: TSPEndpointHandle;
fWriteHandle: TSPEndpointHandle;
procedure CreatePipe; virtual; abstract;
procedure DestroyPipe; virtual; abstract;
procedure ConnectPipe; virtual; abstract;
procedure DisconnectPipe; virtual; abstract;
procedure Initialize(IsServer: Boolean; EndpointMode: TSPEndpointMode); virtual;
procedure Finalize; virtual;
public
destructor Destroy; override;
Function PeekBytes: TMemSize; virtual; // returns number of unread bytes in the pipe
Function Read(out Buffer; Count: TMemSize): TMemSize; virtual;
Function Write(const Buffer; Count: TMemSize): TMemSize; virtual;
property IsServer: Boolean read fIsServer;
property EndpointMode: TSPEndpointMode read fEndpointMode;
property ReadHandle: TSPEndpointHandle read fReadHandle;
property WriteHandle: TSPEndpointHandle read fWriteHandle;
end;
{===============================================================================
--------------------------------------------------------------------------------
TSimplePipe
--------------------------------------------------------------------------------
===============================================================================}
type
TSPConnectionData = packed record
ValidData: UInt32; // 0 = invalid, !0 = valid
CreatorPID: UInt32;
EndpointHandle: Int64;
end;
PSPConnectionData = ^TSPConnectionData;
{===============================================================================
TSimplePipe - class declaration
===============================================================================}
type
TSimplePipe = class(TPipeBase)
protected
fConnectionDataPtr: PSPConnectionData;
procedure CreatePipe; override;
procedure DestroyPipe; override;
procedure ConnectPipe; override;
procedure DisconnectPipe; override;
end;
{===============================================================================
--------------------------------------------------------------------------------
TAnonymousPipe
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TAnonymousPipe - class declaration
===============================================================================}
type
TAnonymousPipe = class(TSimplePipe)
protected
fConnectionData: TSPConnectionData;
procedure Initialize(IsServer: Boolean; EndpointMode: TSPEndpointMode); override;
public
constructor CreateReadEnd;
constructor CreateWriteEnd{$IFNDEF FPC}(Dummy: Integer = 0){$ENDIF};
constructor ConnectReadEnd(ConnectionData: TSPConnectionData);
constructor ConnectWriteEnd(ConnectionData: TSPConnectionData{$IFNDEF FPC}; Dummy: Integer = 0{$ENDIF});
property ConnectionData: TSPConnectionData read fConnectionData;
end;
TPipe = class(TAnonymousPipe);
{===============================================================================
--------------------------------------------------------------------------------
TSharedPipe
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TSharedPipe - class declaration
===============================================================================}
type
TSharedPipe = class(TSimplePipe)
protected
fName: String;
fConnectionDataItem: TNamedSharedItem;
procedure Initialize(IsServer: Boolean; EndpointMode: TSPEndpointMode); override;
procedure Finalize; override;
public
constructor CreateReadEnd(const Name: String);
constructor CreateWriteEnd(const Name: String{$IFNDEF FPC}; Dummy: Integer = 0{$ENDIF});
constructor ConnectReadEnd(const Name: String{$IFNDEF FPC}; Dummy: Single = 0.0{$ENDIF});
constructor ConnectWriteEnd(const Name: String{$IFNDEF FPC}; Dummy: String = ''{$ENDIF});
property Name: String read fName;
end;
{===============================================================================
--------------------------------------------------------------------------------
TNamedPipe
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TNamedPipe - class declaration
===============================================================================}
type
TNamedPipe = class(TPipeBase)
protected
fName: String;
procedure CreatePipe; override;
procedure DestroyPipe; override;
procedure ConnectPipe; override;
procedure DisconnectPipe; override;
procedure InitializeName(IsServer: Boolean; EndpointMode: TSPEndpointMode; const Name: String); virtual;
public
constructor CreateReadEnd(const Name: String);
constructor CreateWriteEnd(const Name: String{$IFNDEF FPC}; Dummy: Integer = 0{$ENDIF});
constructor ConnectReadEnd(const Name: String{$IFNDEF FPC}; Dummy: Single = 0.0{$ENDIF});
constructor ConnectWriteEnd(const Name: String{$IFNDEF FPC}; Dummy: String = ''{$ENDIF});
property Name: String read fName;
end;
implementation
uses
{$IFDEF Windows}
Windows, StrUtils,
StrRect,
{$ENDIF}
InterlockedOps;
{===============================================================================
Externals
===============================================================================}
{$IFNDEF Windows}
const
O_CLOEXEC = $80000;
FIONREAD = $541B;
type
TFDPair = array[0..1] of cInt;
PFDPair = ^TFDPair;
Function errno_ptr: pcInt; cdecl; external name '__errno_location';
Function getpid: pid_t; cdecl; external;
Function pipe2(pipefd: PFDPair; flags: cInt): cInt; cdecl; external;
Function mkfifo(pathname: PChar; mode: mode_t): cInt; cdecl; external;
Function unlink(pathname: PChar): cInt; cdecl; external;
Function open(pathname: PChar; flags: cInt; mode: mode_t): cInt; cdecl; external;
Function close(fd: cInt): cInt; cdecl; external;
Function sys_read(fd: cInt; buf: Pointer; count: size_t): ssize_t; cdecl; external name 'read';
Function sys_write(fd: cInt; buf: Pointer; count: size_t): ssize_t; cdecl; external name 'write';
Function ioctl(fd: cInt; request: cULong): cInt; cdecl; external; varargs;
{$ENDIF}
{===============================================================================
--------------------------------------------------------------------------------
TPipeBase
--------------------------------------------------------------------------------
===============================================================================}
type
TSPParamInt = {$IFDEF Windows}DWORD{$ELSE}cInt{$ENDIF};
{===============================================================================
TPipeBase - class implementation
===============================================================================}
{-------------------------------------------------------------------------------
TPipeBase - protected methods
-------------------------------------------------------------------------------}
procedure TPipeBase.Initialize(IsServer: Boolean; EndpointMode: TSPEndpointMode);
begin
fIsServer := IsServer;
fEndpointMode := EndpointMode;
fReadHandle := {$IFDEF Windows}INVALID_HANDLE_VALUE{$ELSE}-1{$ENDIF};
fWriteHandle := {$IFDEF Windows}INVALID_HANDLE_VALUE{$ELSE}-1{$ENDIF};
If fISServer then
CreatePipe
else
ConnectPipe;
end;
//------------------------------------------------------------------------------
procedure TPipeBase.Finalize;
begin
If fISServer then
DestroyPipe
else
DisconnectPipe;
end;
{-------------------------------------------------------------------------------
TPipeBase - public methods
-------------------------------------------------------------------------------}
destructor TPipeBase.Destroy;
begin
Finalize;
inherited;
end;
//------------------------------------------------------------------------------
Function TPipeBase.PeekBytes: TMemSize;
var
BytesInPipe: TSPParamInt;
begin
If fEndpointMode = emRead then
begin
{$IFDEF Windows}
If PeekNamedPipe(fReadHandle,nil,0,nil,@BytesInPipe,nil) then
Result := TMemSize(BytesInPipe)
else
raise ESPPeekError.CreateFmt('TPipeBase.PeekBytes: Failed to peed pipe (%d).',[GetLastError]);
{$ELSE}
If ioctl(fReadHandle,FIONREAD,@BytesInPipe) = 0 then
Result := TMemSize(BytesInPipe)
else
raise ESPPeekError.CreateFmt('TPipeBase.PeekBytes: Failed to peed pipe (%d).',[errno_ptr^]);
{$ENDIF}
end
else raise ESPInvalidMode.Create('TPipeBase.PeekBytes: Cannot peek from write end.');
end;
//------------------------------------------------------------------------------
Function TPipeBase.Read(out Buffer; Count: TMemSize): TMemSize;
var
BytesRead: TSPParamInt;
begin
If fEndpointMode = emRead then
begin
BytesRead := 0;
{$IFDEF Windows}
If Windows.ReadFile(fReadHandle,Addr(Buffer)^,DWORD(Count),BytesRead,nil) then
Result := TMemSize(BytesRead)
else
raise ESPReadError.CreateFmt('TPipeBase.Read: Read failed (%d).',[GetLastError]);
{$ELSE}
BytesRead := sys_read(fReadHandle,@Buffer,size_t(Count));
If BytesRead >= 0 then
Result := TMemSize(BytesRead)
else
raise ESPReadError.CreateFmt('TPipeBase.Read: Read failed (%d).',[errno_ptr^]);
{$ENDIF}
end
else raise ESPInvalidMode.Create('TPipeBase.Read: Cannot read from write end.');
end;
//------------------------------------------------------------------------------
Function TPipeBase.Write(const Buffer; Count: TMemSize): TMemSize;
var
BytesWritten: TSPParamInt;
begin
If fEndpointMode = emWrite then
begin
BytesWritten := 0;
{$IFDEF Windows}
If Windows.WriteFile(fWriteHandle,Buffer,DWORD(Count),BytesWritten,nil) then
Result := TMemSize(BytesWritten)
else
raise ESPWriteError.CreateFmt('TPipeBase.Write: Write failed (%d).',[GetLastError]);
{$ELSE}
BytesWritten := sys_write(fWriteHandle,@Buffer,size_t(Count));
If BytesWritten >= 0 then
Result := TMemSize(BytesWritten)
else
raise ESPWriteError.CreateFmt('TPipeBase.Write: Write failed (%d).',[errno_ptr^]);
{$ENDIF}
end
else raise ESPInvalidMode.Create('TPipeBase.Write: Cannot write to read end.');
end;
{===============================================================================
--------------------------------------------------------------------------------
TSimplePipe
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TSimplePipe - class implementation
===============================================================================}
{-------------------------------------------------------------------------------
TSimplePipe - protected methods
-------------------------------------------------------------------------------}
procedure TSimplePipe.CreatePipe;
{$IFDEF Windows}
var
SecAttr: TSecurityAttributes;
begin
SecAttr.nLength := SizeOf(TSecurityAttributes);
SecAttr.lpSecurityDescriptor := nil;
SecAttr.bInheritHandle := True;
If not Windows.CreatePipe(fReadHandle,fWriteHandle,@SecAttr,0) then
raise ESPSystemError.CreateFmt('TSimplePipe.CreatePipe: Failed to create pipe (%d).',[GetLastError]);
fConnectionDataPtr^.CreatorPID := UInt32(GetCurrentProcessID);
{$ELSE}
var
Handles: TFDPair;
begin
If pipe2(@Handles,O_CLOEXEC) <> 0 then
raise ESPSystemError.CreateFmt('TSimplePipe.CreatePipe: Failed to create pipe (%d).',[errno_ptr^]);
fReadHandle := Handles[0];
fWriteHandle := Handles[1];
fConnectionDataPtr^.CreatorPID := UInt32(getpid);
{$ENDIF}
// note the reverse - when in read mode, store write handle, and vice-versa
case fEndpointMode of
emRead: fConnectionDataPtr^.EndpointHandle := Int64(PtrInt(fWriteHandle));
emWrite: fConnectionDataPtr^.EndpointHandle := Int64(PtrInt(fReadHandle));
else
raise ESPInvalidMode.CreateFmt('TSimplePipe.CreatePipe: Invalid endpoint mode (%d).',[Ord(fEndpointMode)]);
end;
InterlockedStore(fConnectionDataPtr^.ValidData,1);
end;
//------------------------------------------------------------------------------
procedure TSimplePipe.DestroyPipe;
begin
InterlockedStore(fConnectionDataPtr^.ValidData,0);
FillChar(fConnectionDataPtr^,SizeOf(TSPConnectionData),0);
{$IFDEF Windows}CloseHandle{$ELSE}close{$ENDIF}(fReadHandle);
{$IFDEF Windows}CloseHandle{$ELSE}close{$ENDIF}(fWriteHandle);
end;
//------------------------------------------------------------------------------
procedure TSimplePipe.ConnectPipe;
Function ConnectPipeInternal({$IFNDEF Windows}Param: TSPParamInt{$ENDIF}): TSPEndpointHandle;
{$IFDEF Windows}
var
SourceProcess: THandle;
begin
SourceProcess := OpenProcess(PROCESS_DUP_HANDLE,False,fConnectionDataPtr^.CreatorPID);
If SourceProcess <> 0 then
try
If not Windows.DuplicateHandle(SourceProcess,THandle(PtrInt(fConnectionDataPtr^.EndpointHandle)),GetCurrentProcess,@Result,0,True,DUPLICATE_SAME_ACCESS) then
raise ESPHandleDupError.CreateFmt('TSimplePipe.ConnectPipe.ConnectPipeInternal: Failed to duplicate handle (%d).',[GetLastError]);
finally
CloseHandle(SourceProcess);
end
else raise ESPHandleDupError.CreateFmt('TSimplePipe.ConnectPipe.ConnectPipeInternal: Failed to open source process (%d).',[GetLastError]);
{$ELSE}
begin
{
Open symlink file "/proc/[pid]/fd/[file_descriptor]" - it links to the
anonymous pipe end given in the connection data.
}
Result := open(PChar(Format('/proc/%d/fd/%d',[fConnectionDataPtr^.CreatorPID,fConnectionDataPtr^.EndpointHandle])),O_CLOEXEC or Param,0);
If Result < 0 then
raise ESPSystemError.CreateFmt('TSimplePipe.ConnectPipe.ConnectPipeInternal: Failed to connect named pipe (%d).',[errno_ptr^]);
{$ENDIF}
end;
begin
If InterlockedLoad(fConnectionDataPtr^.ValidData) <> 0 then
begin
case fEndpointMode of
emRead: fReadHandle := ConnectPipeInternal({$IFNDEF Windows}O_RDONLY{$ENDIF});
emWrite: fWriteHandle := ConnectPipeInternal({$IFNDEF Windows}O_WRONLY{$ENDIF});
else
raise ESPInvalidMode.CreateFmt('TSimplePipe.ConnectPipe: Invalid endpoint mode (%d).',[Ord(fEndpointMode)]);
end;
end
else raise ESPNoServer.Create('TSimplePipe.ConnectPipe: No server to connect to.');
end;
//------------------------------------------------------------------------------
procedure TSimplePipe.DisconnectPipe;
begin
case fEndpointMode of
emRead: {$IFDEF Windows}CloseHandle{$ELSE}close{$ENDIF}(fReadHandle);
emWrite: {$IFDEF Windows}CloseHandle{$ELSE}close{$ENDIF}(fWriteHandle);
else
raise ESPInvalidMode.CreateFmt('TSimplePipe.DisconnectPipe: Invalid endpoint mode (%d).',[Ord(fEndpointMode)]);
end;
end;
{===============================================================================
--------------------------------------------------------------------------------
TAnonymousPipe
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TAnonymousPipe - class implementation
===============================================================================}
{-------------------------------------------------------------------------------
TAnonymousPipe - protected methods
-------------------------------------------------------------------------------}
procedure TAnonymousPipe.Initialize(IsServer: Boolean; EndpointMode: TSPEndpointMode);
begin
fConnectionDataPtr := @fConnectionData;
inherited Initialize(IsServer,EndpointMode);
end;
{-------------------------------------------------------------------------------
TAnonymousPipe - public methods
-------------------------------------------------------------------------------}
constructor TAnonymousPipe.CreateReadEnd;
begin
inherited Create;
Initialize(True,emRead);
end;
//------------------------------------------------------------------------------
constructor TAnonymousPipe.CreateWriteEnd{$IFNDEF FPC}(Dummy: Integer = 0){$ENDIF};
begin
inherited Create;
Initialize(True,emWrite);
end;
//------------------------------------------------------------------------------
constructor TAnonymousPipe.ConnectReadEnd(ConnectionData: TSPConnectionData);
begin
inherited Create;
fConnectionData := ConnectionData;
Initialize(False,emRead);
end;
//------------------------------------------------------------------------------
constructor TAnonymousPipe.ConnectWriteEnd(ConnectionData: TSPConnectionData{$IFNDEF FPC}; Dummy: Integer = 0{$ENDIF});
begin
inherited Create;
fConnectionData := ConnectionData;
Initialize(False,emWrite);
end;
{===============================================================================
--------------------------------------------------------------------------------
TSharedPipe
--------------------------------------------------------------------------------
===============================================================================}
const
SP_SHARED_NAMESPACE = 'shared_pipes';
{===============================================================================
TSharedPipe - class implementation
===============================================================================}
{-------------------------------------------------------------------------------
TSharedPipe - protected methods
-------------------------------------------------------------------------------}
procedure TSharedPipe.Initialize(IsServer: Boolean; EndpointMode: TSPEndpointMode);
begin
fConnectionDataItem := TNamedSharedItem.Create(fName,SizeOf(TSPConnectionData),SP_SHARED_NAMESPACE);
fConnectionDataPtr := PSPConnectionData(fConnectionDataItem.Memory);
inherited Initialize(IsServer,EndpointMode);
end;
//------------------------------------------------------------------------------
procedure TSharedPipe.Finalize;
begin
inherited;
fConnectionDataItem.Free;
end;
{-------------------------------------------------------------------------------
TSharedPipe - public methods
-------------------------------------------------------------------------------}
constructor TSharedPipe.CreateReadEnd(const Name: String);
begin
inherited Create;
fName := Name;
Initialize(True,emRead);
end;
//------------------------------------------------------------------------------
constructor TSharedPipe.CreateWriteEnd(const Name: String{$IFNDEF FPC}; Dummy: Integer = 0{$ENDIF});
begin
inherited Create;
fName := Name;
Initialize(True,emWrite);
end;
//------------------------------------------------------------------------------
constructor TSharedPipe.ConnectReadEnd(const Name: String{$IFNDEF FPC}; Dummy: Single = 0.0{$ENDIF});
begin
inherited Create;
fName := Name;
Initialize(False,emRead);
end;
//------------------------------------------------------------------------------
constructor TSharedPipe.ConnectWriteEnd(const Name: String{$IFNDEF FPC}; Dummy: String = ''{$ENDIF});
begin
inherited Create;
fName := Name;
Initialize(False,emWrite);
end;
{===============================================================================
--------------------------------------------------------------------------------
TNamedPipe
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TNamedPipe - class implementation
===============================================================================}
{-------------------------------------------------------------------------------
TNamedPipe - protected methods
-------------------------------------------------------------------------------}
procedure TNamedPipe.CreatePipe;
procedure CreatePipeInternal(Param: TSPParamInt; out PipeHandle: TSPEndpointHandle);
{$IFDEF Windows}
var
ErrCode: DWORD;
begin
PipeHandle := CreateNamedPipeW(PWideChar(StrToWinW(fName)),Param,PIPE_TYPE_BYTE,1,0,0,INFINITE,nil);
If PipeHandle <> INVALID_HANDLE_VALUE then
begin
If not ConnectNamedPipe(PipeHandle,nil) then
begin
ErrCode := GetLastError;
If ErrCode <> ERROR_PIPE_CONNECTED then
raise ESPSystemError.CreateFmt('TNamedPipe.CreatePipe.CreatePipeInternal: Failed to connect named pipe (%d).',[ErrCode]);
end;
end
else raise ESPSystemError.CreateFmt('TNamedPipe.CreatePipe.CreatePipeInternal: Failed to create named pipe (%d).',[GetLastError]);
{$ELSE}
begin
If mkfifo(PChar(fName),S_IRUSR or S_IWUSR or S_IRGRP or S_IWGRP or S_IROTH or S_IWOTH) <> 0 then
raise ESPSystemError.CreateFmt('TNamedPipe.CreatePipe.CreatePipeInternal: Failed to create named pipe (%d).',[errno_ptr^]);
PipeHandle := open(PChar(fName),O_CLOEXEC or Param,0);
If PipeHandle < 0 then
raise ESPSystemError.CreateFmt('TNamedPipe.CreatePipe.CreatePipeInternal: Failed to connect named pipe (%d).',[errno_ptr^]);
{$ENDIF}
end;
begin
case fEndpointMode of
emRead: CreatePipeInternal({$IFDEF Windows}PIPE_ACCESS_INBOUND{$ELSE}O_RDONLY{$ENDIF},fReadHandle);
emWrite: CreatePipeInternal({$IFDEF Windows}PIPE_ACCESS_OUTBOUND{$ELSE}O_WRONLY{$ENDIF},fWriteHandle);
else
raise ESPInvalidMode.CreateFmt('TNamedPipe.CreatePipe: Invalid endpoint mode (%d).',[Ord(fEndpointMode)]);
end;
end;
//------------------------------------------------------------------------------
procedure TNamedPipe.DestroyPipe;
procedure DestroyPipeInternal(PipeHandle: TSPEndpointHandle);
begin
{$IFDEF Windows}
FlushFileBuffers(PipeHandle);
DisconnectNamedPipe(PipeHandle);
CloseHandle(PipeHandle);
{$ELSE}
close(PipeHandle);
unlink(PChar(fName));
{$ENDIF}
end;
begin
case fEndpointMode of
emRead: DestroyPipeInternal(fReadHandle);
emWrite: DestroyPipeInternal(fWriteHandle);
else
raise ESPInvalidMode.CreateFmt('TNamedPipe.DestroyPipe: Invalid endpoint mode (%d).',[Ord(fEndpointMode)]);
end;
end;
//------------------------------------------------------------------------------
procedure TNamedPipe.ConnectPipe;
procedure ConnectPipeInternal(Param: TSPParamInt; out PipeHandle: TSPEndpointHandle);
begin
{$IFDEF Windows}
PipeHandle := CreateFileW(PWideChar(StrToWinW(fName)),Param,0,nil,OPEN_EXISTING,0,0);
If PipeHandle = INVALID_HANDLE_VALUE then
raise ESPSystemError.CreateFmt('TNamedPipe.ConnectPipe.ConnectPipeInternal: Failed to connect named pipe (%d).',[GetLastError]);
{$ELSE}
PipeHandle := open(PChar(fName),O_CLOEXEC or Param,0);
If PipeHandle < 0 then
raise ESPSystemError.CreateFmt('TNamedPipe.ConnectPipe.ConnectPipeInternal: Failed to connect named pipe (%d).',[errno_ptr^]);
{$ENDIF}
end;
begin
case fEndpointMode of
emRead: ConnectPipeInternal({$IFDEF Windows}GENERIC_READ{$ELSE}O_RDONLY{$ENDIF},fReadHandle);
emWrite: ConnectPipeInternal({$IFDEF Windows}GENERIC_WRITE{$ELSE}O_WRONLY{$ENDIF},fWriteHandle);
else
raise ESPInvalidMode.CreateFmt('TNamedPipe.ConnectPipe: Invalid endpoint mode (%d).',[Ord(fEndpointMode)]);
end;
end;
//------------------------------------------------------------------------------
procedure TNamedPipe.DisconnectPipe;
begin
case fEndpointMode of
emRead: {$IFDEF Windows}CloseHandle{$ELSE}close{$ENDIF}(fReadHandle);
emWrite: {$IFDEF Windows}CloseHandle{$ELSE}close{$ENDIF}(fWriteHandle);
else
raise ESPInvalidMode.CreateFmt('TNamedPipe.DisconnectPipe: Invalid endpoint mode (%d).',[Ord(fEndpointMode)]);
end;
end;
//------------------------------------------------------------------------------
procedure TNamedPipe.InitializeName(IsServer: Boolean; EndpointMode: TSPEndpointMode; const Name: String);
var
i: TStrOff;
begin
// assign and rectify name
fName := AnsiLowerCase(Name);
{$IFDEF Windows}
// replace all backslashes (not allowed) with underscores
For i := 1 to Length(fName) do
If fName[i] = '\' then
fName[i] := '_';
// prepend required string
If not AnsiStartsText('\\.\pipe\',fName) then
fName := '\\.\pipe\' + fName;
// limit length
If Length(fName) > 256 then
SetLength(fName,256);
{$ELSE}
// replace all path delimiters with underscores
For i := 1 to Length(fName) do
If fName[i] = '/' then
fName[i] := '_';
fName := '/tmp/fifo_' + fName;
{$ENDIF}
Initialize(IsServer,EndpointMode);
end;
{-------------------------------------------------------------------------------
TNamedPipe - public methods
-------------------------------------------------------------------------------}
constructor TNamedPipe.CreateReadEnd(const Name: String);
begin
inherited Create;
InitializeName(True,emRead,Name);
end;
//------------------------------------------------------------------------------
constructor TNamedPipe.CreateWriteEnd(const Name: String{$IFNDEF FPC}; Dummy: Integer = 0{$ENDIF});
begin
inherited Create;
InitializeName(True,emWrite,Name);
end;
//------------------------------------------------------------------------------
constructor TNamedPipe.ConnectReadEnd(const Name: String{$IFNDEF FPC}; Dummy: Single = 0.0{$ENDIF});
begin
inherited Create;
InitializeName(False,emRead,Name);
end;
//------------------------------------------------------------------------------
constructor TNamedPipe.ConnectWriteEnd(const Name: String{$IFNDEF FPC}; Dummy: String = ''{$ENDIF});
begin
inherited Create;
InitializeName(False,emWrite,Name);
end;
end.