首頁 > 軟體

Node.js程序管理之Process模組詳解

2022-07-06 14:01:52

在前面Node.js事件執行機制也有提到,Node.js應用在單個執行緒執行,但是現在大部分伺服器都是多處理器,為了方便使用多個程序,Node.js提供了3個模組。Process模組提供了存取正在執行的程序。child_process模組可以建立子程序,並與他們通訊。cluster模組提供了實現共用相同埠的叢集服務能力,允許多個請求同時處理。

一、Process模組

Process模組是一個無須使用require()就可以從node.js應用程式進行存取的全域性物件。

二、程序I/O管道

Process為程序stdin、stdout、stderr提供了對標準I/O管道的存取。(有點了類似C++的輸入輸出的趕腳)

stdin輸入,stdout、stderr可以實現輸出

/**
 * Created by Administrator on 2016/3/29.
 */
process.stdin.on('data',function(data){
    process.stdout.write(data.toString());
    process.stderr.write(data.toString());
});

輸出結果:

"C:Program Files (x86)JetBrainsWebStorm 11.0.3binrunnerw.exe" F:nodejsnode.exe Process.js
ssss
ssss
ssss

三、程序的訊號

說起訊號讓我想起了號誌,雖然它們不是一回事,剛才也百度了下,算是複習重溫一下。

由於號誌只能進行兩種操作等待和傳送訊號,即P(sv)和V(sv),他們的行為是這樣的:

由於號誌只能進行兩種操作等待和傳送訊號,即P(sv)和V(sv),他們的行為是這樣的:

P(sv):如果sv的值大於零,就給它減1;如果它的值為零,就掛起該程序的執行

V(sv):如果有其他程序因等待sv而被掛起,就讓它恢復執行,如果沒有程序因等待sv而掛起,就給它加1.

兩個程序共用號誌sv,一旦其中一個程序執行了P(sv)操作,它將得到號誌,並可以進入臨界區,使sv減1。而第二個程序將被阻止進入臨界區,因為當它試圖執行P(sv)時,sv為0,它會被掛起以等待第一個程序離開臨界區域並執行V(sv)釋放號誌,這時第二個程序就可以恢復執行。

Node.js允許註冊監聽器來處理作業系統傳送給一個程序的訊號。可以被傳送的node.js程序的事件有下面幾個:

SIGUSR1 :啟動偵錯程式時發出。

SIGPIPE:程序試圖寫入在另一端沒有程序連線的管道時發出

SIGHUP:Window上控制檯關閉視窗時發出。在發出此事件約10秒會終止Node.js

SIGTERM:在發出一個終止程序的請求時發出.Windwo不支援。

SIGINT:當中斷被傳送到這個程序上,如Ctrl+C組合鍵被按下時發出

SIGBEAK:Windwo下Ctrl+Break組合鍵被按下時發出。

SIGWINCE:在控制檯已經被調整大小時發出。Window下,只有當你寫入控制檯,移動遊標或者在原始模式下使用可讀的TTY時發出

SIGKILL:程序殺掉時發出

SIGSTOP:程序終止時發出。

監聽的其實不止上面的訊號在process的on定義中也能看出還有exit、uncaughtException等(可以轉到定義)。

四、控制程序執行

abort():使當前的Node.js應用程式發出abort事件,退出,併產生一個記憶體核心轉儲檔案

exit([code]):使當前Node.js應用退出,並返回指定的code

kill(pid,[signall]):作業系統會向指定的pid的程序傳送一個kill訊號,預設是SIGTERM

nexttick(callback):排程node.js程式的佇列中的callback函數

五、從Process模組獲取資訊

var util = require('util');
//返回程序的當前工作目錄
console.log('Current directory: ' + process.cwd());
//該程序的環境中指定的鍵/值對
console.log('Environment Settings: ' + JSON.stringify(process.env));
//用於啟動Node.js應用程式的命令引數
console.log('Node Args: ' + process.argv);
//Node。js從中啟動的絕對路徑
console.log('Execution Path: ' + process.execPath);
//用於啟動應用程式的特定節點的命令列選項
console.log('Execution Args: ' + JSON.stringify(process.execArgv));
//Node.js版本號
console.log('Node Version: ' + process.version);
//提供一個物件,包含Node.js應用程式所需的模組和版本
console.log('Module Versions: ' +  JSON.stringify(process.versions));
//用於編譯當前節點可執行程式的設定選項
console.log('Node Config: ' +  JSON.stringify(process.config));
//當前程序ID
console.log('Process ID: ' + process.pid);
//當前程序標題
console.log('Process Title: ' + process.title);
//作業系統
console.log('Process Platform: ' + process.platform);
//程序正在執行的處理器體系結構
console.log('Process Architecture: ' + process.arch);
//Node.js程序的當前記憶體使用情況可使用util.inspect()讀取
console.log('Memory Usage: ' + util.inspect(process.memoryUsage()));
//返回一個高精確的時間
var start = process.hrtime();
setTimeout(function() {
  var delta = process.hrtime(start);
  console.log('High-Res timer took %d seconds and %d nanoseconds', 
              delta[0], + delta[1]);
  console.log('Node has been running %d seconds', process.uptime());
}, 1000);

輸出結果:

"C:Program Files (x86)JetBrainsWebStorm 11.0.3binrunnerw.exe" F:nodejsnode.exe process_info.js
Current directory: c:UsersAdministratorDesktopnodejs-mongodb-angularjs-web-development-masterch09
Environment Settings: {"#envTSLOGTSLOG11328":"100839136","ALLUSERSPROFILE":"C:\ProgramData","APPDATA":"C:\Users\Administrator\AppData\Roaming","asl.log":"Destination=file","CommonProgramFiles":"C:\Program Files\Common Files","CommonProgramFiles(x86)":"C:\Program Files (x86)\Common Files","CommonProgramW6432":"C:\Program Files\Common Files","COMPUTERNAME":"LENOVO-PC","ComSpec":"C:\WINDOWS\system32\cmd.exe","configsetroot":"C:\WINDOWS\ConfigSetRoot","FPS_BROWSER_APP_PROFILE_STRING":"Internet Explorer","FPS_BROWSER_USER_PROFILE_STRING":"Default","FP_NO_HOST_CHECK":"NO","HOMEDRIVE":"C:","HOMEPATH":"\Users\Administrator","LOCALAPPDATA":"C:\Users\Administrator\AppData\Local","LOGONSERVER":"\\MicrosoftAccount","NUMBER_OF_PROCESSORS":"4","OS":"Windows_NT","Path":"C:\PROGRAM FILES (X86)\INTEL\ICLS CLIENT\;C:\PROGRAM FILES\INTEL\ICLS CLIENT\;C:\WINDOWS\SYSTEM32;C:\WINDOWS;C:\WINDOWS\SYSTEM32\WBEM;C:\WINDOWS\SYSTEM32\WINDOWSPOWERSHELL\V1.0\;C:\PROGRAM FILES\INTEL\INTEL(R) MANAGEMENT ENGINE COMPONENTS\DAL;C:\PROGRAM FILES\INTEL\INTEL(R) MANAGEMENT ENGINE COMPONENTS\IPT;C:\PROGRAM FILES (X86)\INTEL\INTEL(R) MANAGEMENT ENGINE COMPONENTS\DAL;C:\PROGRAM FILES (X86)\INTEL\INTEL(R) MANAGEMENT ENGINE COMPONENTS\IPT;C:\PROGRAM FILES (X86)\ATI TECHNOLOGIES\ATI.ACE\CORE-STATIC;;C:\WINDOWS\SYSTEM32;C:\WINDOWS;C:\WINDOWS\SYSTEM32\WBEM;C:\WINDOWS\SYSTEM32\WINDOWSPOWERSHELL\V1.0\;C:\PROGRAM FILES (X86)\AMD\ATI.ACE\CORE-STATIC;C:\Program Files\Lenovo\Bluetooth Software\;C:\Program Files\Lenovo\Bluetooth Software\syswow64;F:\nodejs\;C:\WINDOWS\system32\config\systemprofile\.dnx\bin;C:\Program Files\Microsoft DNX\Dnvm\;C:\Program Files (x86)\Lenovo\Lenovo Home\DCMainWin.exe;C:\Users\Administrator\AppData\Roaming\npm","PATHEXT":".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC","PROCESSOR_ARCHITECTURE":"AMD64","PROCESSOR_IDENTIFIER":"Intel64 Family 6 Model 60 Stepping 3, GenuineIntel","PROCESSOR_LEVEL":"6","PROCESSOR_REVISION":"3c03","ProgramData":"C:\ProgramData","ProgramFiles":"C:\Program Files","ProgramFiles(x86)":"C:\Program Files (x86)","ProgramW6432":"C:\Program Files","PSModulePath":"C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\","PUBLIC":"C:\Users\Public","SESSIONNAME":"Console","SystemDrive":"C:","SystemRoot":"C:\WINDOWS","TEMP":"C:\Users\ADMINI~1\AppData\Local\Temp","TMP":"C:\Users\ADMINI~1\AppData\Local\Temp","USERDOMAIN":"LENOVO-PC","USERDOMAIN_ROAMINGPROFILE":"LENOVO-PC","USERNAME":"Administrator","USERPROFILE":"C:\Users\Administrator","VS140COMNTOOLS":"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools\","windir":"C:\WINDOWS"}
Node Args: F:nodejsnode.exe,c:UsersAdministratorDesktopnodejs-mongodb-angularjs-web-development-masterch09process_info.js
Execution Path: F:nodejsnode.exe
Execution Args: []
Node Version: v4.3.2
Module Versions: {"http_parser":"2.5.2","node":"4.3.2","v8":"4.5.103.35","uv":"1.8.0","zlib":"1.2.8","ares":"1.10.1-DEV","icu":"56.1","modules":"46","openssl":"1.0.2g"}
Node Config: {"target_defaults":{"cflags":[],"default_configuration":"Release","defines":[],"include_dirs":[],"libraries":[]},"variables":{"asan":0,"host_arch":"x64","icu_data_file":"icudt56l.dat","icu_data_in":"../../deps/icu/source/data/in\icudt56l.dat","icu_endianness":"l","icu_gyp_path":"tools/icu/icu-generic.gyp","icu_locales":"en,root","icu_path":"deps\icu","icu_small":true,"icu_ver_major":"56","node_byteorder":"little","node_install_npm":true,"node_prefix":"/usr/local","node_release_urlbase":"","node_shared_http_parser":false,"node_shared_libuv":false,"node_shared_openssl":false,"node_shared_zlib":false,"node_tag":"","node_use_dtrace":false,"node_use_etw":true,"node_use_lttng":false,"node_use_openssl":true,"node_use_perfctr":true,"openssl_fips":"","openssl_no_asm":0,"python":"C:\Python27\python.exe","target_arch":"x64","v8_enable_gdbjit":0,"v8_enable_i18n_support":1,"v8_no_strict_aliasing":1,"v8_optimized_debug":0,"v8_random_seed":0,"v8_use_snapshot":true,"want_separate_host_toolset":0}}
Process ID: 8124
Process Title: C:Program Files (x86)JetBrainsWebStorm 11.0.3binrunnerw.exe
Process Platform: win32
Process Architecture: x64
Memory Usage: { rss: 17641472, heapTotal: 7409232, heapUsed: 3756584 }
High-Res timer took 1 seconds and 107153 nanoseconds
Node has been running 1.128 seconds

Process finished with exit code 0

到此這篇關於Node.js程序管理之Process模組的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com