2016-09-15 292 views
0

我已經催生了一個子進程,下面是代碼:如何爲子進程產生孫子進程?

const spawn = require('child_process').spawn; 
const ls = spawn('ls', ['-lh', '/usr'], { detached: true }); 

ls.stdout.on('data', (data) => { 
    console.log(`stdout: ${data}`); 
    fs.writeFileSync('path-to-test.txt', 'stdout'); 
}); 

ls.stderr.on('data', (data) => { 
    console.log(`stderr: ${data}`); 
    fs.writeFileSync('path-to-test.txt', 'stderr'); 
}); 

ls.on('close', (code) => { 
    console.log(`child process exited with code ${code}`); 
}); 

隨着選項detached: true,它將保持孩子進程中運行,即使父進程被殺死。

我的問題是:如何在這個子進程下運行孫子進程?因爲在我的senario中,產生這個子進程後,父進程將被終止。所以我不能產生另一個進程,除了使用現有的子進程來產生孫子進程。

回答

0

首先,重要的是要注意,分離的選項只會在父系死於Windows系統之後使子代保持活動狀態。在Unix系統中,孩子會默認保持活動狀態。

爲了產生「孫子過程」,child_program.js也必須產生子過程。試試這個例子看看。假設你有app.js其中包含以下內容:

const spawn = require('child_process').spawn; 

const child = spawn(process.argv[0], [__dirname + '/child_program.js'], { 
detached: true, 
stdio: 'ignore' 
}); 

child.unref(); 

然後想,child_program.js包含以下內容:

const spawn = require('child_process').spawn; 

const child = spawn(process.argv[0], [__dirname + '/grandchild_program.js'], { 
detached: true, 
stdio: 'ignore' 
}); 

child.unref(); 

最後,讓我們說grandchild_program.js做到這一點:

var fs = require('fs'); 

fs.writeFileSync(__dirname + '/bob.txt', 'bob was here', 'utf-8'); 

創建這些文件,把它們放在同一個目錄下,運行node app.js,然後你應該看到bob.txt顯示在那個文件夾中我的目錄。如果您有任何問題,請告訴我。我的問題是,如果你知道process.argv[0]給你什麼,以及你爲什麼用這個論點產生新的子進程。

+0

我知道process.argv [0]的值來自命令行參數,但我很抱歉,我在那裏輸入了錯誤的代碼,現在已經被修正。所以我只有一個帶有子進程的文件'app.js'來運行一個簡單的命令,然後它應該產生一個孫子進程來運行另一個簡單的命令。而已。 –

+1

@ Ng2-Fun:你誤解了子進程是什麼。你不運行一個子進程來運行一個簡單的命令。這個簡單的命令是你的子進程。 – slebetman

+0

@slebetman - 感謝您糾正我。 –