在前面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模块的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持脚本之家。