Repository navigation
Expand file tree
/
Copy pathUnixProcess.class.st
More file actions
1940 lines (1565 loc) · 63.2 KB
/
Copy pathUnixProcess.class.st
File metadata and controls
1940 lines (1565 loc) · 63.2 KB
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
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"
I represent the Unix operating system process in which this Squeak session is running. I collaborate with an instance of UnixOSProcessAccessor to provide access to the external operating system. My instance variables are updated when my process accessor changes, allowing them to be monitored with a Smalltalk inspector.
"
Class {
#name : #UnixProcess,
#superclass : #ThisOSProcess,
#instVars : [
'ppid',
'pthread',
'path',
'programName',
'arguments',
'environment'
],
#category : #'OSProcess-Unix'
}
{ #category : #utility }
UnixProcess class >> arguments [
"UnixProcess arguments"
^ self thisOSProcess arguments
]
{ #category : #examples }
UnixProcess class >> backgroundProcessInHeadlessSqueak [
"Demonstrate running a ''batch job'' in a low priority background Squeak,
with output written to an OSPipe. This Squeak image reads data from the
pipe and displays it on the Transcript. The background Squeak will write
enough data to block an OSPipe, so the foreground Squeak loops while
reading available data up to end of file.
Open a Transcript, then '' inspect it '' on this method. Process runs
indefinitely, so terminate the process to end demo."
"UnixProcess backgroundProcessInHeadlessSqueak"
^ [[| pipe backgroundJob ws s |
pipe := OSPipe new.
backgroundJob := OSProcess thisOSProcess
forkHeadlessSqueakAndDoThenQuit: [| beers |
OSProcess accessor nice: 1. "lower priority of background OS process"
beers := [:i | (i < 1 ifTrue: ['no more'] ifFalse: [i asString])
, ' bottle' , (i = 1 ifTrue: [''] ifFalse: ['s'])].
(99 to: 1 by: -1) do: [:count | pipe nextPutAll:
(beers value: count) , ' of beer on the wall, '
, (beers value: count) , ' of beer' , String cr
, 'take one down and pass it around, '
, (beers value: count - 1) , ' of beer on the wall'; cr].
pipe close].
WorldState addDeferredUIMessage:
[Transcript show: backgroundJob asString , ' started'; cr].
pipe closeWriter. "don't need writer end, close it before the #upToEnd"
"pipe writer blocks when pipe full, so we need to loop while reading to end "
ws := WriteStream on: String new.
[backgroundJob isComplete] whileFalse:
[(Delay forMilliseconds: 200) wait.
(s := pipe upToEnd) ifNotNil: [ws nextPutAll: s]].
pipe close.
WorldState addDeferredUIMessage:
[Transcript show: backgroundJob asString
, ' completed, display results in 2 seconds'; cr].
(Delay forSeconds: 2) wait.
WorldState addDeferredUIMessage:
[Transcript show: ws contents.
Transcript cr; show: 'delay 5 seconds before forking next Squeak job'; cr].
(Delay forSeconds: 5) wait] repeat]
forkAt: Processor userBackgroundPriority
]
{ #category : #'X display - deprecated' }
UnixProcess class >> canConnectToXDisplay: xDisplayName [
"Deprecated. See ThisOSProcess>canConnectToXDisplay:"
"self canConnectToXDisplay: ':0.0' "
^ self thisOSProcess canConnectToXDisplay: xDisplayName
]
{ #category : #examples }
UnixProcess class >> catAFile [
"Copy contents of a file to standard output. This demonstrates reassigning stdin to an open FileStream."
"UnixProcess catAFile"
| in proc |
in := OSProcess readOnlyFileNamed: '/etc/hosts'.
proc := self forkJob: '/bin/cat'
arguments: nil
environment: nil
descriptors: (Array with: in with: nil with: nil).
in close.
proc ifNil: [self noAccessorAvailable].
^ proc
]
{ #category : #examples }
UnixProcess class >> catFromFileToFiles [
"Copy contents of a file to another file, with any error messages going
to a third file."
"UnixProcess catFromFileToFiles"
| in out err proc |
in := OSProcess readOnlyFileNamed: '/etc/hosts'.
out := OSProcess newFileNamed: '/tmp/deleteMe.out'.
err := OSProcess newFileNamed: '/tmp/deleteMe.err'.
proc := UnixProcess
forkJob: '/bin/cat'
arguments: nil
environment: nil
descriptors: (Array
with: in
with: out
with: err).
in close.
out close.
err close.
proc ifNil: [self noAccessorAvailable].
^ proc
]
{ #category : #examples }
UnixProcess class >> clientServerDemo [
"Start a new headless instance of Squeak running in a child OS process. The new
instance is a nearly identical copy of its parent, resuming execution at the same
point as the parent. The child process will run a TCP server process in the headless
image, then exit. Test results are written to the Transcript.
Answer '127 0 0 1' in response to the host address dialog."
"UnixProcess clientServerDemo"
| proc |
proc := self forkHeadlessSqueakAndDoThenQuit: [Socket remoteTestServerTCP].
proc ifNotNil: [Socket remoteTestClientTCP].
^ proc
]
{ #category : #examples }
UnixProcess class >> clientServerDemo2 [
"Start a new instance of Squeak running in a child OS process. The new
instance is a nearly identical copy of its parent, resuming execution at
the same point as the parent. The child process will run a TCP server
process, then exit. Test results are written to the Transcript. "
"UnixProcess clientServerDemo2"
| remotePort remoteHost serverBlock socket buffer n bytesToSend sendBuf
receiveBuf done bytesSent bytesReceived packetsSent packetsReceived t |
remotePort := 54321.
remoteHost := 'localhost'.
serverBlock :=
[Transcript clear; cr; show: 'This is the server Squeak session'; cr.
Socket initializeNetworkIfFail: [^ nil].
socket := Socket newTCP.
socket listenOn: remotePort.
buffer := String new: 4000.
socket waitForConnectionUntil: Socket standardDeadline.
[socket isConnected]
whileTrue: [socket dataAvailable
ifTrue:
[n := socket receiveDataInto: buffer.
socket sendData: buffer count: n]].
socket closeAndDestroy].
(UnixProcess forkSqueakAndDoThenQuit: serverBlock)
ifNil: [self noAccessorAvailable. ^ nil].
Transcript cr; show: 'This is the client Squeak session'; cr.
Transcript show: 'starting client/server TCP test'; cr.
Transcript show: 'initializing network ... '.
Socket initializeNetworkIfFail: [^ Transcript show: 'failed'].
Transcript show: 'ok'; cr.
socket := Socket newTCP.
socket connectTo: (NetNameResolver addressForName: remoteHost) port: remotePort.
socket waitForConnectionUntil: Socket standardDeadline.
Transcript show: 'client endpoint created'; cr.
bytesToSend := 1000000.
sendBuf := String new: 4000 withAll: $x.
receiveBuf := String new: 50000.
done := false.
bytesSent := bytesReceived := packetsSent := packetsReceived := 0.
t := Time
millisecondsToRun:
[[done]
whileFalse:
[(socket sendDone and: [bytesSent < bytesToSend])
ifTrue:
[packetsSent := packetsSent + 1.
bytesSent := bytesSent + (socket sendData: sendBuf)].
socket dataAvailable
ifTrue:
[packetsReceived := packetsReceived + 1.
bytesReceived := bytesReceived + (socket receiveDataInto: receiveBuf)].
done := bytesSent >= bytesToSend].
[bytesReceived < bytesToSend]
whileTrue: [socket dataAvailable
ifTrue:
[packetsReceived := packetsReceived + 1.
bytesReceived := bytesReceived + (socket receiveDataInto: receiveBuf)]]].
socket closeAndDestroy.
Transcript show: 'remoteClient TCP test done; time = ' , t printString; cr.
Transcript show: packetsSent printString , ' packets, ' , bytesSent printString ,
' bytes sent (' , (bytesSent * 1000 // t) printString , ' bytes/sec)'; cr.
Transcript show: packetsReceived printString , ' packets, ' , bytesReceived printString ,
' bytes received (' , (bytesReceived * 1000 // t) printString , ' bytes/sec)'; cr.
^ bytesReceived
]
{ #category : #examples }
UnixProcess class >> cloneSqueak [
"Start a new instance of Squeak running in a child OS process. The new instance is a
nearly identical copy of its parent, resuming execution at the same point as the
parent, and differentiated only by the return value of this method."
"UnixProcess cloneSqueak"
| proc |
proc := self forkSqueak.
proc ifNil: [self noAccessorAvailable].
^ proc
]
{ #category : #'X display - deprecated' }
UnixProcess class >> currentXDisplayName [
"Deprecated. See ThisOSProcess>>currentXDisplayName"
"self currentXDisplayName"
^ self thisOSProcess currentXDisplayName
]
{ #category : #'X display - deprecated' }
UnixProcess class >> decapitate [
"Deprecated. See ThisOSProcess>>decapitate"
"self decapitate"
^ OSProcess thisOSProcess decapitate
]
{ #category : #'X display - deprecated' }
UnixProcess class >> displayOnXServer: xDisplayName [
"Deprecated. See ThisOSProcess>>displayOnXServer"
"self displayOnXServer: ':0.0' "
"self displayOnXServer: 'unix:0' "
"self displayOnXServer: ':1' "
"self displayOnXServer: 'noSuchMachine'"
"self displayOnXServer: 'noSuchMachine:0'" "<-make sure network is running first!"
^ OSProcess thisOSProcess displayOnXServer: xDisplayName
]
{ #category : #examples }
UnixProcess class >> eightLeafSqueakTree [
"Clone this squeak three times, resulting in a total of (2 raisedTo: 3) nearly identical
squeaks. Have a look at the pidArray inspectors and to the debug messages on stdout
in order to see what is going on. The tree of processes looks like this:
111
+--------+--------+
| | |
011 101 110
+---+ |
| | 100
010 001
|
000
"
"UnixProcess eightLeafSqueakTree inspect"
| depth this pidArray debugString |
depth := 3.
this := OSProcess thisOSProcess.
this stdOut ifNil: [self noAccessorAvailable. ^ nil].
pidArray := Array new: depth.
(1 to: depth) do: [ :e | | p pid |
p := this forkSqueak.
pid := (p == this) ifTrue: [0] ifFalse: [p pid]. "Use Unix fork(2) convention"
pidArray at: e put: pid].
debugString := 'pid ', (this pid printString), ' ppid ', (this ppid printString), ' ',
(pidArray printString), (Character lf asString).
this stdOut nextPutAll: debugString.
^ pidArray
]
{ #category : #utility }
UnixProcess class >> env [
"Note: The #environment selector has special meaning for classes, so use #env."
"UnixProcess env"
^ self thisOSProcess environment
]
{ #category : #'child process creation' }
UnixProcess class >> forkHeadlessSqueakAndDo: aBlock [
"Start a new instance of Squeak running in a child OS process, and
execute aBlock in the child instance. The new instance is a clone of
this image, but without a connection to the X display. The child instance
executes aBlock, which hopefully does not involve interaction with the
X display; and the parent continues normally.
The child should not depend on using existing connections to external
resources. For example, the child may lose its connections to stdin,
stdout, and stderr after its parent exits."
"UnixProcess forkHeadlessSqueakAndDo: [UnixProcess helloWorld]"
^ self thisOSProcess forkHeadlessSqueakAndDo: aBlock
]
{ #category : #'child process creation' }
UnixProcess class >> forkHeadlessSqueakAndDoThenQuit: aBlock [
"Start a new instance of Squeak running in a child OS process, and
execute aBlock in the child instance. The new instance is a clone of
this image, but without a connection to the X display. The child instance
executes aBlock, which hopefully does not involve interaction with the
X display; and the parent continues normally.
The child should not depend on using existing connections to external
resources. For example, the child may lose its connections to stdin, stdout,
and stderr after its parent exits."
"UnixProcess forkHeadlessSqueakAndDoThenQuit: [UnixProcess helloWorld]"
^ self thisOSProcess forkHeadlessSqueakAndDoThenQuit: aBlock
]
{ #category : #'child process creation' }
UnixProcess class >> forkJob: executableFile arguments: arrayOfStrings environment: stringDictionary descriptors: arrayOf3Streams [
"Call Unix vfork() and execve() to create a child process, and answer the
child process. Delegate this to the singleton OSProcess>>thisOSProcess."
^ self thisOSProcess
forkJob: executableFile
arguments: arrayOfStrings
environment: stringDictionary
descriptors: arrayOf3Streams
]
{ #category : #'child process creation' }
UnixProcess class >> forkSqueak [
"Start a new instance of Squeak running in a child OS process. The new instance is a
clone of this image except for the return value of this method. It does not reload the
image file from disk.
The child should not depend on using existing connections to external resources. For
example, the child may lose its connections to stdin, stdout, and stderr after its parent
exits."
"UnixProcess forkSqueak"
^ self thisOSProcess forkSqueak.
]
{ #category : #'child process creation' }
UnixProcess class >> forkSqueakAndDo: aBlock [
"Start a new instance of Squeak running in a child OS process. The new instance is a
clone of this image except for the return value of this method. It does not reload the
image file from disk. The child image evaluates aBlock.
The child should not depend on using existing connections to external resources. For
example, the child may lose its connections to stdin, stdout, and stderr after its parent
exits."
"UnixProcess forkSqueakAndDo:
[Object inform: 'Hi, I am the child Squeak process.']"
^ self thisOSProcess forkSqueakAndDo: aBlock
]
{ #category : #'child process creation' }
UnixProcess class >> forkSqueakAndDoThenQuit: aBlock [
"Start a new instance of Squeak running in a child OS process. The new instance is a
clone of this image except for the return value of this method. It does not reload the
image file from disk. The child image evaluates aBlock.
The child should not depend on using existing connections to external resources. For
example, the child may lose its connections to stdin, stdout, and stderr after its parent
exits."
"UnixProcess forkSqueakAndDoThenQuit:
[Object inform: 'Hi, I am the child Squeak process. Click OK to exit the child Squeak.']"
^ self thisOSProcess forkSqueakAndDoThenQuit: aBlock
]
{ #category : #examples }
UnixProcess class >> headlessChild [
"Start a new instance of Squeak running in a child OS process. The new
instance is a nearly identical copy of its parent, resuming execution at the
same point as the parent, and differentiated only by the return value of
this method. The child squeak will write a message to standard output,
then exit."
"UnixProcess headlessChild"
| this childBlock |
this := OSProcess thisOSProcess.
childBlock :=
[this stdOut nextPutAll: 'hello world from child process '.
this pid printOn: OSProcess thisOSProcess stdOut.
this stdOut nextPut: Character lf ].
^ self forkHeadlessSqueakAndDoThenQuit: childBlock
]
{ #category : #'platform identification' }
UnixProcess class >> isResponsibleForThisPlatform [
"Answer true if this class is responsible for representing the OS process for
the Squeak VM running on the current platform."
^ self isUnix
]
{ #category : #examples }
UnixProcess class >> listDirectory [
"Execute a simple command, sending output to standard output."
"UnixProcess listDirectory"
| proc |
proc := self
forkJob: '/bin/ls'
arguments: nil
environment: nil
descriptors: nil.
proc ifNil: [self noAccessorAvailable].
^ proc
]
{ #category : #'utility - VM building' }
UnixProcess class >> makeVmIn: buildDirectoryPathName [
"Rebuild the virtual machine and plugins in the buildDirectoryPathName
directory. If the build is successful, save the image and restart using the
new VM. This assumes that the currently executing VM is either located in,
or linked to, the buildDirectoryPathName directory."
"UnixProcess makeVmIn: '/usr/local/squeak/Squeak-2.8/build'"
"UnixProcess makeVmIn: nil"
^ self makeVmIn: (buildDirectoryPathName ifNil: ['']) interactive: true
]
{ #category : #'utility - VM building' }
UnixProcess class >> makeVmIn: buildDirectoryPathName interactive: aBoolean [
"Rebuild the virtual machine and plugins in the buildDirectoryPathName
directory. If the build is successful, save the image and restart using the
new VM. This assumes that the currently executing VM is either located in,
or linked to, the buildDirectoryPathName directory. If aBoolean is true,
display interactive dialogs, otherwise output goes only to the Transcript."
"UnixProcess makeVmIn: '/usr/local/squeak/Squeak-2.8/build' interactive: true"
| commandString result |
commandString := 'cd ', buildDirectoryPathName, '; make'.
Transcript cr; show: 'running external command "', commandString, '"'; cr.
result := self waitForCommandOutputArray: commandString.
((result at: 3) == 0 and: [(result at: 2) isEmpty])
ifTrue:
[Transcript show: 'make completed successfully, restarting VM'; cr.
aBoolean ifTrue:
[self inform: 'make completed successfully, restarting VM'].
self quitAndRestart]
ifFalse:
[Transcript show: (result at: 2); cr.
Transcript show: 'make did not succeed, VM will not be restarted'; cr.
aBoolean ifTrue:
[self inform: 'make did not succeed, VM will not be restarted'.
self inform: (result at: 2)]].
^ result
]
{ #category : #utility }
UnixProcess class >> path [
"UnixProcess path"
^ self thisOSProcess path
]
{ #category : #utility }
UnixProcess class >> programName [
"UnixProcess programName"
^ self thisOSProcess programName
]
{ #category : #'X display - deprecated' }
UnixProcess class >> recapitate [
"Deprecated. See ThisOSProcess>>recapitate"
"self decapitate. (Delay forSeconds: 5) wait. self recapitate."
^ OSProcess thisOSProcess recapitate
]
{ #category : #utility }
UnixProcess class >> restartVirtualMachine [
"Fork a new instance and quit this one. This moves the running VM into a new
OS process, and starts a new X display for the new process. It does not reload the
VM program text, so this cannot be used to restart the VM after rebuild."
"UnixProcess restartVirtualMachine"
| proc |
proc := self forkSqueak.
proc isNil
ifTrue:
[self noAccessorAvailable.
nil]
ifFalse:
[OSProcess thisOSProcess == proc
ifFalse:
["Quit if this is the parent process"
Smalltalk quitPrimitive]].
^ proc
]
{ #category : #'unit tests' }
UnixProcess class >> runTests [
"Run a few tests to see if things are working correctly on Unix/Linux.
Output is on stdout, stderr, and the Squeak Transcript. One of the tests
requires input from stdin, so Squeak should be run from a shell command
line and not as a background process.
Warning: This test will crash your VM if your are using the -xshm command
line option. For reasons which I do not quite understand, the X shared
memory segment becomes invalid when the Squeak VM which initially
opened the shared memory exits. The remaining Squeak children will crash
when then then next try to update the display.
Note: If you see 'select: Bad file descriptor' messages on your console standard
output, these are occuring while running headless in the decapitate/recapitate
tests.
Important: Prior to evaluating this method, please type one line of text
followed by a <cr> on the terminal standard input. This provides the
input for the stdin test. Failing to provide this input prior to evaluating
the tests will cause one of the test cases to fail."
"UnixProcess runTests"
| this s p failures result a |
failures := 0.
Transcript show: 'Begin OSProcess tests'; cr.
Transcript show: 'Test for working ProcessAccessor ... '.
this := OSProcess thisOSProcess.
(this pid isKindOf: Integer)
ifTrue: [Transcript show: 'OK'; cr]
ifFalse: [Transcript show: 'NFG'; cr. failures := failures + 1].
Transcript show: 'Echo one line of text previously entered from stdin ... '.
s := OSProcess readFromStdIn.
s size > 0
ifTrue: [Transcript show: 'OK'; cr; show: s; cr]
ifFalse: [Transcript show: 'NFG'; cr. failures := failures + 1].
Transcript show: 'Message to stdout ... '.
(OSProcess helloWorld isKindOf: AttachableFileStream)
ifTrue: [Transcript show: 'OK'; cr; show: s; cr]
ifFalse: [Transcript show: 'NFG'; cr. failures := failures + 1].
Transcript show: 'Message to stderr ... '.
(OSProcess helloStdErr isKindOf: AttachableFileStream)
ifTrue: [Transcript show: 'OK'; cr; show: s; cr]
ifFalse: [Transcript show: 'NFG'; cr. failures := failures + 1].
Transcript show: 'UnixProcess cataFile ... '.
p := UnixProcess catAFile.
(Delay forSeconds: 1) wait.
p exitStatus == 0
ifTrue: [Transcript show: 'OK'; cr]
ifFalse: [Transcript show: 'NFG'; cr. failures := failures + 1].
Transcript show: 'UnixProcess testEnvSet ... '.
p := UnixProcess testEnvSet.
(Delay forSeconds: 1) wait.
p exitStatus == 0
ifTrue: [Transcript show: 'OK'; cr]
ifFalse: [Transcript show: 'NFG'; cr. failures := failures + 1].
Transcript show: 'UnixProcess catFromFileToFiles ... '.
OSProcess command: 'rm /tmp/deleteMe.out'.
OSProcess command: 'rm /tmp/deleteMe.err'.
p := UnixProcess catFromFileToFiles.
(Delay forSeconds: 1) wait.
p exitStatus == 0
ifTrue: [Transcript show: 'OK'; cr]
ifFalse: [Transcript show: 'NFG'; cr. failures := failures + 1].
Transcript show: 'UnixProcess testRunCommand ... '.
OSProcess command: 'rm /tmp/deleteMe.out'.
OSProcess command: 'rm /tmp/deleteMe.err'.
p := UnixProcess testRunCommand.
(Delay forSeconds: 1) wait.
p exitStatus == 256
ifTrue: [Transcript show: 'OK'; cr]
ifFalse: [Transcript show: 'NFG'; cr. failures := failures + 1].
Transcript show: 'UnixProcess testPipe ... '.
UnixProcess testPipe = 'this is some text to write into the pipe'
ifTrue: [Transcript show: 'OK'; cr]
ifFalse: [Transcript show: 'NFG'; cr. failures := failures + 1].
Transcript show: 'UnixProcess testPipeLine ... '.
UnixProcess testPipeLine = 'This is the text to write out through one pipe, copy through an external cat command, and then read back in through another pipe.'
ifTrue: [Transcript show: 'OK'; cr]
ifFalse: [Transcript show: 'NFG'; cr. failures := failures + 1].
Transcript show: 'UnixProcess spawnTenHeadlessChildren ... '.
p := UnixProcess spawnTenHeadlessChildren.
(p size == 10 and: [(p select: [:e | (e runState == #running) | (e exitStatus == 0)]) size == 10])
ifTrue: [Transcript show: 'OK'; cr]
ifFalse: [Transcript show: 'NFG'; cr. failures := failures + 1].
Transcript show: 'UnixProcess cloneSqueak ... '.
p := UnixProcess cloneSqueak.
(p isKindOf: UnixProcess)
ifTrue:
[(Delay forSeconds: 1) wait.
OSProcess snapshot: false andQuit: true].
(Delay forSeconds: 5) wait.
p exitStatus == 0
ifTrue: [Transcript show: 'OK'; cr]
ifFalse: [Transcript show: 'NFG'; cr. failures := failures + 1].
Transcript show: 'UnixProcess squeakSqueak ... '.
p := UnixProcess squeakSqueak.
(Delay forSeconds: 5) wait.
OSProcess thisOSProcess sigkill: p.
(Delay forSeconds: 1) wait.
p exitStatus == 9
ifTrue: [Transcript show: 'OK'; cr]
ifFalse: [Transcript show: 'NFG'; cr. failures := failures + 1].
Transcript show: 'UnixProcess restartVirtualMachine ... '.
p := UnixProcess restartVirtualMachine.
p pid == OSProcess thisOSProcess pid
ifTrue: [Transcript show: 'OK'; cr]
ifFalse: [Transcript show: 'NFG'; cr. failures := failures + 1].
Transcript show: 'UnixProcess command: ''cat'' input: ''this is some test data'' ... '.
p := (OSProcess thisOSProcess
command: 'cat'
input: 'this is some test data').
(Delay forSeconds: 1) wait.
p upToEnd = 'this is some test data'
ifTrue: [Transcript show: 'OK'; cr]
ifFalse: [Transcript show: 'NFG'; cr. failures := failures + 1].
Transcript show: 'UnixProcess waitForCommandOutput: ''echo sleeping...; sleep 1; echo I just slept for one second'' ... '.
('*I just slept for one second*' match:
(OSProcess thisOSProcess
waitForCommandOutput: 'echo sleeping...; sleep 1; echo I just slept for one second'))
ifTrue: [Transcript show: 'OK'; cr]
ifFalse: [Transcript show: 'NFG'; cr. failures := failures + 1].
Transcript show: 'Unix command pipeline with output and error returned in an array ... '.
(Smalltalk hasClassNamed: #PipeableOSProcess)
ifTrue:
[a := (((Smalltalk at: #PipeableOSProcess) command: 'echo this is a test; BOGUS') | 'cut -c11-14') outputAndError.
(((a isKindOf: Array)
and: ['test*' match: (a at: 1)])
and: ['*BOGUS*' match: (a at: 2)])
ifTrue: [Transcript show: 'OK'; cr]
ifFalse: [Transcript show: 'NFG'; cr. failures := failures + 1]]
ifFalse:
[Transcript show: 'skipping PipeableOSProcess test (requires CommandShell)'; cr].
Transcript show: 'UnixProcess decapitate and recapatiate five times'; cr.
5 timesRepeat:
[UnixProcess decapitate.
UnixProcess recapitate].
failures == 1
ifTrue: [result := 'OSProcess tests completed with ', failures printString, ' failure']
ifFalse: [result := 'OSProcess tests completed with ', failures printString, ' failures'].
Transcript show: result; cr.
^ result
]
{ #category : #'utility - image save' }
UnixProcess class >> saveImageInBackground [
"Save image in a background OS process."
"UnixProcess saveImageInBackground"
^ self saveImageInBackground: self uniqueNameForSavedImage nice: false
]
{ #category : #'utility - image save' }
UnixProcess class >> saveImageInBackground: savedImageName nice: niceFlag [
"When Squeak is used as a server it is sometimes desirable to periodically
save image snapshots. This method forks a headless Squeak to perform a
snapshot without impacting the server Squeak. Very little additional memory
is required to do this because Unix copy-on-write memory management allows
the two Squeak images to share object memory while the save is performed.
The saved image is given a time stamped name, and the image name of
the main server Squeak remains unchanged. If niceFlag is true, the
background OS process runs at lowered scheduling priority."
^ self forkHeadlessSqueakAndDo:
[| st |
"Delay is required in the background process when forking a headless
Squeak, probably necessary to permit X session stuff to settle down."
(Delay forMilliseconds: 500) wait.
(niceFlag notNil and: [niceFlag]) ifTrue:
["lower priority of background OS process"
OSProcess accessor nice: 1].
st := SmalltalkImage current.
(SourceFiles at: 2) ifNotNil:
["ensure that copying the changes file will always work"
st closeSourceFiles.
OSProcess saveChangesInFileNamed: (st fullNameForChangesNamed: savedImageName)].
st changeImageNameTo: savedImageName,'.image';
closeSourceFiles;
openSourceFiles; "so SNAPSHOT appears in new changes file"
saveImageSegments;
snapshot: true andQuit: true]
]
{ #category : #'utility - image save' }
UnixProcess class >> saveImageInBackgroundNicely [
"Save image in a background OS process with lowered scheduling priority."
"UnixProcess saveImageInBackgroundNicely"
^ self saveImageInBackground: self uniqueNameForSavedImage nice: true
]
{ #category : #utility }
UnixProcess class >> sessionID [
"UnixProcess sessionID"
^ self thisOSProcess sessionID
]
{ #category : #'X display - deprecated' }
UnixProcess class >> setXDisplayName: xDisplayName [
"Deprecated. See ThisOSProcess>>setXDisplayName"
"self setXDisplayName: 'unix:0' "
"self setXDisplayName: ':1' "
^ OSProcess thisOSProcess setXDisplayName: xDisplayName
]
{ #category : #examples }
UnixProcess class >> spawnTenHeadlessChildren [
"Spawn ten Squeak children, each of which writes a message to standard
output, then exits. Answer an array of pid values for the child
processes. "
"UnixProcess spawnTenHeadlessChildren"
| childBlock count children this |
this := OSProcess thisOSProcess.
this stdOut ifNil: [self noAccessorAvailable. ^ nil].
count := 10.
children := Array new: count.
childBlock :=
[this stdOut nextPutAll: 'hello world from child process '.
this pid printOn: this stdOut.
this stdOut nextPut: Character lf.
this stdOut flush].
(1 to: count)
do:
[:e |
OSProcess thisOSProcess stdOut flush.
children at: e put: (self forkHeadlessSqueakAndDoThenQuit: childBlock)].
^ children
]
{ #category : #examples }
UnixProcess class >> squeakSqueak [
"Start a new instance of Squeak running in a child OS process. The new instance
will restart from the image file, so it is a clone of this image as it existed at the
most recent image save. See cloneSqueak for an example of how to clone the
running image without going back to the saved image file."
"UnixProcess squeakSqueak"
| proc |
proc := self squeak.
proc ifNil: [self noAccessorAvailable].
^ proc
]
{ #category : #utility }
UnixProcess class >> startSwiki: aSwiki onPort: num loggingTo: aFileName [
"Start a swiki in a headless Squeak image."
"UnixProcess startSwiki: 'myswiki' onPort: 8081 loggingTo: 'log.txt'"
| proc |
(Smalltalk hasClassNamed: #SwikiAction)
ifTrue:
[proc := self forkSqueakAndDo:
[(Smalltalk at: #SwikiAction) new restore: 'myswiki'.
(Smalltalk at: #PWS) serveOnPort: num loggingTo: aFileName.
UnixProcess decapitate].
proc ifNil: [self noAccessorAvailable].
^ proc]
ifFalse:
[self notify: 'PWS not installed in this image']
]
{ #category : #utility }
UnixProcess class >> stdErr [
"UnixProcess stdErr"
^ self thisOSProcess stdErr
]
{ #category : #utility }
UnixProcess class >> stdIn [
"UnixProcess stdIn"
^ self thisOSProcess stdIn
]
{ #category : #utility }
UnixProcess class >> stdOut [
"UnixProcess stdOut"
^ self thisOSProcess stdOut
]
{ #category : #examples }
UnixProcess class >> testEnvSet [
"Set up a new environment for a child process. Exec a shell to show the
environment variables on the terminal standard output. Note that many
shells will set other environment variables in addition to those which we
set up prior to executing the shell."
"UnixProcess testEnvSet"
| e proc |
e := Dictionary new.
e at: #KEY1 put: 'value1';
at: #KEY2 put: 'value2';
at: #KEY3 put: 'value3'.
proc := self
forkJob: '/bin/sh'
arguments: #('-c' 'env' )
environment: e
descriptors: nil.
proc ifNil: [self noAccessorAvailable].
^ proc
]
{ #category : #examples }
UnixProcess class >> testPipe [
"Create an OS pipe, write some text to it, and read the text back from the
other end of the pipe."
"UnixProcess testPipe inspect"
| s p r |
s := 'this is some text to write into the pipe'.
p := OSPipe new.
p ifNil:
[self noAccessorAvailable.
^ p].
p writer nextPutAll: s.
p writer close.
r := p reader next: s size.
p reader close.
^ r
]
{ #category : #examples }
UnixProcess class >> testPipeLine [
"Create two OS pipes, and a child OS process with its input connected to
one pipe and its output connected to the other pipe. Write some text to
the input pipe, and read the resulting output (just echoed back by the
Unix cat command) back through the output pipe. Send a SIGHUP signal
to the child process to tell it to exit.
This test verifies the ability of Squeak to send text to an external OS process
through a pipe, and read the output text back from another pipe.
See ConnectedUnixProcess for a more useful implementation."
"UnixProcess testPipeLine inspect"
| testString pipe1 pipe2 input output src dest desc result child |
OSProcess accessor canAccessSystem ifFalse: [^ nil].
testString := 'This is the text to write out through one pipe, copy through an external cat command, and then read back in through another pipe.'.
pipe1 := OSPipe blockingPipe.
pipe2 := OSPipe nonBlockingPipe.
input := pipe1 reader.
output := pipe2 writer.
src := pipe1 writer.
dest := pipe2 reader.
desc := Array
with: input
with: output
with: nil.
child := self
forkJob: '/bin/cat'
arguments: nil
environment: nil
descriptors: desc.
input close.
output close.
src nextPutAll: testString.
src close.
(Delay forSeconds: 1) wait.
result := dest next: testString size.
dest close.
child sigterm. "Tell the child to exit"
^ result
]
{ #category : #examples }
UnixProcess class >> testRunCommand [
"Run the command 'ls -l /etc /etc/noSuchFile'. The output of the
command will be in the file '/tmp/deleteMe.out', and the error output
will be in '/tmp/deleteMe.err'. "
"UnixProcess testRunCommand"
| out err desc args proc |
out := OSProcess newFileNamed: '/tmp/deleteMe.out'.
err := OSProcess newFileNamed: '/tmp/deleteMe.err'.
desc := Array
with: nil
with: out
with: err.
args := Array
with: '-l'
with: '/etc'
with: '/etc/noSuchFile'
with: '/etc/anotherNonexistentFile'.
proc := self
forkJob: '/bin/ls'
arguments: args
environment: nil
descriptors: desc.
proc ifNil: [self noAccessorAvailable].
out close.
err close.
^ proc
]
{ #category : #'utility - image save' }
UnixProcess class >> uniqueNameForSavedImage [
"A time stamped image name that will sort in date order in a directory listing"
"UnixProcess uniqueNameForSavedImage"
| now month day hour minute second |
now := DateAndTime now.
month := now month asString.
day := now dayOfMonth asString.
hour := now hour24 asString.
minute := now minute asString.
second := now second asString.
^ 'squeak-',
now year asString,
(month size < 2 ifTrue: ['0', month] ifFalse: [month]),
(day size < 2 ifTrue: ['0', day] ifFalse: [day]),
(hour size < 2 ifTrue: ['0', hour] ifFalse: [hour]),
(minute size < 2 ifTrue: ['0', minute] ifFalse: [minute]),
(second size < 2 ifTrue: ['0', second] ifFalse: [second])
]
{ #category : #'external command processing' }
UnixProcess class >> waitForCommandOutput: aCommandString [
"Run a command in a shell process. Similar to the system(3) call in the
standard C library. The active Smalltalk process waits for completion of
the external command process."