Node.js進程管理之Process模塊詳解

在前面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)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" F:\nodejs\node.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)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" F:\nodejs\node.exe process_info.js
Current directory: c:\Users\Administrator\Desktop\nodejs-mongodb-angularjs-web-development-master\ch09
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:\nodejs\node.exe,c:\Users\Administrator\Desktop\nodejs-mongodb-angularjs-web-development-master\ch09\process_info.js
Execution Path: F:\nodejs\node.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)\JetBrains\WebStorm 11.0.3\bin\runnerw.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模塊的文章就介紹到這瞭。希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: