2323const common = require ( '../common' ) ;
2424const assert = require ( 'assert' ) ;
2525const cluster = require ( 'cluster' ) ;
26+ const fs = require ( 'fs' ) ;
27+ const http = require ( 'http' ) ;
2628
2729const totalWorkers = 2 ;
2830
2931// Cluster setup
3032if ( cluster . isWorker ) {
31- const http = require ( 'http' ) ;
33+ const filepath = `${ process . env . filedir } /${ process . pid } -test-cluster-primary-error` ;
34+ fs . writeFileSync ( filepath , 'hello' ) ;
35+ process . on ( 'exit' , ( ) => {
36+ fs . unlinkSync ( filepath ) ;
37+ } ) ;
3238 http . Server ( ( ) => { } ) . listen ( 0 , '127.0.0.1' ) ;
3339} else if ( process . argv [ 2 ] === 'cluster' ) {
3440 // Send PID to testcase process
@@ -66,14 +72,20 @@ if (cluster.isWorker) {
6672 cluster . fork ( ) ;
6773} else {
6874 // This is the testcase
69-
75+ const tmpdir = require ( '../common/tmpdir' ) ;
76+ tmpdir . refresh ( ) ;
77+ // Make sure the child process have write permission
78+ fs . chmodSync ( tmpdir . path , 0o777 ) ;
7079 const fork = require ( 'child_process' ) . fork ;
7180
7281 // List all workers
7382 const workers = [ ] ;
7483
7584 // Spawn a cluster process
76- const primary = fork ( process . argv [ 1 ] , [ 'cluster' ] , { silent : true } ) ;
85+ const primary = fork ( process . argv [ 1 ] , [ 'cluster' ] , {
86+ silent : true ,
87+ env : { filedir : tmpdir . path }
88+ } ) ;
7789
7890 // Handle messages from the cluster
7991 primary . on ( 'message' , common . mustCall ( ( data ) => {
@@ -87,13 +99,16 @@ if (cluster.isWorker) {
8799 primary . on ( 'exit' , common . mustCall ( ( code ) => {
88100 // Check that the cluster died accidentally (non-zero exit code)
89101 assert . strictEqual ( code , 1 ) ;
90-
91102 // XXX(addaleax): The fact that this uses raw PIDs makes the test inherently
92103 // flaky – another process might end up being started right after the
93- // workers finished and receive the same PID.
104+ // workers finished and receive the same PID. So we also need to determine
105+ // whether the file created by the process still exists
94106 const pollWorkers = ( ) => {
95107 // When primary is dead all workers should be dead too
96- if ( workers . some ( ( pid ) => common . isAlive ( pid ) ) ) {
108+ if ( workers . some ( ( pid ) => {
109+ const filepath = `${ tmpdir . path } /${ pid } -test-cluster-primary-error` ;
110+ return common . isAlive ( pid ) && fs . existsSync ( filepath ) ;
111+ } ) ) {
97112 setTimeout ( pollWorkers , 50 ) ;
98113 }
99114 } ;
0 commit comments