




已阅读5页,还剩22页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
子进程o 类: ChildProcess 事件: error 事件: exit 事件: close 事件: disconnect 事件: message child.stdin child.stdout child.stderr child.pid child.kill(signal) child.send(message, sendHandle) 例子: 发送一个server对象 示例: 发送socket对象 child.disconnect()o child_process.spawn(command, args, options)o child_process.exec(command, options, callback)o child_process.execFile(file, args, options, callback)o child_process.fork(modulePath, args, options)子进程#稳定度: 3 - 稳定Node 通过child_process模块提供了类似popen(3)的处理三向数据流(stdin/stdout/stderr)的功能。它能够以完全非阻塞的方式与子进程的stdin、stdout和stderr以流式传递数据。(请注意,某些程序在内部使用行缓冲 I/O。这不会影响到 node.js,但您发送到子进程的数据不会被立即消费。)使用require(child_process).spawn()或require(child_process).fork()创建子进程。这两种方法的语义有些区别,下文将会解释。类: ChildProcess#.ChildProcess是一个EventEmitter。子进程有三个与之关联的流:child.stdin、child.stdout和child.stderr。它们可以共享父进程的 stdio 流,也可以作为独立的被导流的流对象。ChildProcess 类不能直接被使用, 使用spawn()或者fork()方法创建一个 Child Process 实例。事件: error.errError Object错误。发生于:1. 进程不能被创建, 或者2. 进程不能被终止掉, 或者3. 由任何原因引起的数据发送到子进程失败.See alsoChildProcess#kill()andChildProcess#send().参阅ChildProcess#kill()和ChildProcess#send()。事件: exit#.codeNumber假如进程正常退出,则为它的退出代码。 signalString假如是被父进程终止,则为所传入的终止子进程的信号。这个事件是在子进程被结束的时候触发的. 假如进程被正常结束,code就是退出进程的指令代码, 否则为null. 假如进程是由于接受到signal结束的,signal就代表着信号的名称, 否则为null.注意子进程的 stdio 流可能仍为开启状态。参阅waitpid(2).事件: close#t.codeNumber假如进程正常退出,则为它的退出代码。 signalString假如是被父进程终止,则为所传入的终止子进程的信号。这个事件会在一个子进程的所有stdio流被终止时触发, 这和exit事件有明显的不同,因为多进程有时候会共享同一个stdio流事件: disconnect#.在子进程或父进程中使用使用.disconnect()方法后,这个事件会被触发,在断开之后,就不可能再相互发送信息了。可以通过检查子进程的child.connected属性是否为true去检查是否可以发送信息事件: message# messageObjecta parsed JSON object or primitive valuesendHandleHandle objecta Socket or Server objectmessageObject一个已解析的JSON对象或者原始类型值 sendHandleHandle object一个socket 或者 server对象Messages send by.send(message, sendHandle)are obtained using themessageevent.通过.send()发送的信息可以通过监听message事件获取到child.stdin#Stream objectStream objectAWritable Streamthat represents the child processsstdin. Closing this stream viaend()often causes the child process to terminate.子进程的stdin是一个可写流,通过end()方法关闭该可写流可以终止子进程,If the child stdio streams are shared with the parent, then this will not be set.假如子进程的stdio流与父线程共享,这个child.stdin不会被设置child.stdout#Stream objectStream objectAReadable Streamthat represents the child processsstdout.子进程的stdout是个可读流.If the child stdio streams are shared with the parent, then this will not be set.假如子进程的stdio流与父线程共享,这个child.stdin不会被设置child.stderr#Stream objectStream objectAReadable Streamthat represents the child processsstderr.子进程的stderr是一个可读流If the child stdio streams are shared with the parent, then this will not be set.假如子进程的stdio流与父线程共享,这个child.stdin不会被设置child.pid#IntegerIntegerThe PID of the child process.子进程的PIDExample:示例:console.log(Spawned child pid: + grep.pid); grep.stdin.end();child.kill(signal)#signalStringsignalStringSend a signal to the child process. If no argument is given, the process will be sentSIGTERM. Seesignal(7)for a list of available signals.发送一个信号给子线程. 假如没有给参数, 将会发送SIGTERM. 参阅signal(7)查看所有可用的signals列表/ send SIGHUP to process grep.kill(SIGHUP);May emit anerrorevent when the signal cannot be delivered. Sending a signal to a child process that has already exited is not an error but may have unforeseen consequences: if the PID (the process ID) has been reassigned to another process, the signal will be delivered to that process instead. What happens next is anyones guess.当一个signal不能被传递的时候,会触发一个error事件, 发送一个信号到已终止的子线程不会发生错误,但是可能引起不可预见的后果, 假如该子进程的ID已经重新分配给了其他进程,signal将会被发送到其他进程上面,大家可以猜想到这发生什么后果。Note that while the function is calledkill, the signal delivered to the child process may not actually kill it.killreally just sends a signal to a process.注意,当函数调用kill, 传递给子进程的信号不会去终结子进程, kill实际上只是发送一个信号到进程而已。Seekill(2)Seekill(2)child.send(message, sendHandle)# messageObjectsendHandleHandle objectmessageObject sendHandleHandle objectWhen usingchild_process.fork()you can write to the child usingchild.send(message, sendHandle)and messages are received by amessageevent on the child.当使用child_process.fork()你可以使用child.send(message, sendHandle)向子进程写数据 and 数据将通过子进程上的message事件接受.For example:例如:n.send( hello: world );And then the child script,sub.jsmight look like this:然后是子进程脚本的代码,sub.js代码如下:process.send( foo: bar );In the child theprocessobject will have asend()method, andprocesswill emit objects each time it receives a message on its channel.在子进程脚本中process对象有send()方法, process每次通过它的信道接收到信息都会触发事件,信息以对象形式返回。There is a special case when sending acmd: NODE_foomessage. All messages containing aNODE_prefix in itscmdproperty will not be emitted in themessageevent, since they are internal messages used by node core. Messages containing the prefix are emitted in theinternalMessageevent, you should by all means avoid using this feature, it is subject to change without notice.不过发送cmd: NODE_foo信息是个比较特殊的情况. 所有在cmd属性中包含 aNODE_前缀的信息将不会触发message事件, 因为他们是由node 核心使用的内部信息. 相反这种信息会触发internalMessage事件, 你应该通过各种方法避免使用这种特性, 他改变的时候不会接收到通知.ThesendHandleoption tochild.send()is for sending a TCP server or socket object to another process. The child will receive the object as its second argument to themessageevent.child.send()的sendHandle选项是用来发送一个TCP服务或者socket对象到另一个线程的,子进程将会接收这个参数作为message事件的第二个参数。Emits anerrorevent if the message cannot be sent, for example because the child process has already exited.假如信息不能被发送,将会触发一个error事件, 比如说因为子线程已经退出了。例子: 发送一个server对象#Here is an example of sending a server:这里是一个发送一个server对象的例子:/ 创建一个handle对象,发送一个句柄. var server = require(net).createServer(); server.on(connection, function (socket) socket.end(handled by parent); ); server.listen(1337, function() child.send(server, server); );And the child would the receive the server object as:同时子进程将会以如下方式接收到这个server对象:process.on(message, function(m, server) if (m = server) server.on(connection, function (socket) socket.end(handled by child); ); );Note that the server is now shared between the parent and child, this means that some connections will be handled by the parent and some by the child.注意,server对象现在有父进程和子进程共享,这意味着某些连接将会被父进程和子进程处理。Fordgramservers the workflow is exactly the same. Here you listen on amessageevent instead ofconnectionand useserver.bindinstead ofserver.listen. (Currently only supported on UNIX platforms.)对dgram服务器,工作流程是一样的, 你监听的是message事件,而不是 connection事件, 使用server.bind ,而不是server.listen.(当前仅在UNIX平台支持)示例: 发送socket对象#Here is an example of sending a socket. It will spawn two children and handle connections with the remote address74.125.127.100as VIP by sending the socket to a special child process. Other sockets will go to a normal process.这是个发送socket的例子. 他将创建两个子线程 ,同时处理连接,这是通过使用远程地址74.125.127.100作为 VIP 发送socket到一个特殊的子线程. 其他的socket将会发送到正常的线程里. / if this is a VIP if (socket.remoteAddress = 74.125.127.100) special.send(socket, socket); return; / just the usual dudes normal.send(socket, socket); ); server.listen(1337);Thechild.jscould look like this:child.js文件代码如下:process.on(message, function(m, socket) if (m = socket) socket.end(You were handled as a + process.argv2 + person); );Note that once a single socket has been sent to a child the parent can no longer keep track of when the socket is destroyed. To indicate this condition the.connectionsproperty becomesnull. It is also recommended not to use.maxConnectionsin this condition.注意,一旦单个的socket被发送到子进程,当这个socket被删除之后,父进程将不再对它保存跟踪,这表明了这个条件下.connetions属性将变成null, 在这个条件下同时也不推荐时间.maxConnectionschild.disconnect()#To close the IPC connection between parent and child use thechild.disconnect()method. This allows the child to exit gracefully since there is no IPC channel keeping it alive. When calling this method thedisconnectevent will be emitted in both parent and child, and theconnectedflag will be set tofalse. Please note that you can also callprocess.disconnect()in the child process.使用child.disconnect()方法关闭父进程与子进程的IPC连接. 他让子进程非常优雅的退出,因为已经没有活跃的IPC信道. 当调用这个方法,disconnect事件将会同时在父进程和子进程内被触发,connected的标签将会被设置成flase, 请注意,你也可以在子进程中调用process.disconnect()child_process.spawn(command, args, options)# commandStringThe command to run argsArrayList of string arguments optionsObjecto cwdStringCurrent working directory of the child processo stdioArray|StringChilds stdio configuration. (See below)o customFdsArrayDeprecatedFile descriptors for the child to use for stdio. (See below)o envObjectEnvironment key-value pairso detachedBooleanThe child will be a process group leader. (See below)o uidNumberSets the user identity of the process. (See setuid(2).)o gidNumberSets the group identity of the process. (See setgid(2).) return:ChildProcess object commandString要运行的命令 argsArray 字符串参数列表 optionsObjecto cwdString 子进程的当前的工作目录o stdioArray|String 子进程 stdio 配置. (参阅下文)o customFdsArrayDeprecated作为子进程 stdio 使用的 文件标示符. (参阅下文)o envObject 环境变量的键值对o detachedBoolean 子进程将会变成一个进程组的领导者. (参阅下文)o uidNumber 设置用户进程的ID. (See setuid(2).)o gidNumber 设置进程组的ID. (See setgid(2).) 返回: ChildProcess objectLaunches a new process with the givencommand, with command line arguments inargs. If omitted,argsdefaults to an empty Array.用给定的命令发布一个子进程,带有args命令行参数,如果省略的话,args默认为一个空数组The third argument is used to specify additional options, which defaults to:第三个参数被用来指定额外的设置,默认是: cwd: undefined, env: process.env cwdallows you to specify the working directory from which the process is spawned. Useenvto specify environment variables that will be visible to the new process.cwd允许你从被创建的子进程中指定一个工作目录. 使用env去指定在新进程中可用的环境变量.Example of runningls -lh /usr, capturingstdout,stderr, and the exit code:一个运行ls -lh /usr的例子, 获取stdout,stderr, 和退出代码:ls.on(close, function (code) console.log(child process exited with code + code); );Example: A very elaborate way to run ps ax | grep ssh例子: 一个非常精巧的方法执行 ps ax | grep sshgrep.on(close, function (code) if (code != 0) console.log(grep process exited with code + code); );Example of checking for failed exec:检查执行错误的例子:child.stderr.setEncoding(utf8); child.stderr.on(data, function (data) if (/execvp()/.test(data) console.log(Failed to start child process.); );Note that if spawn receives an empty options object, it will result in spawning the process with an empty environment rather than usingprocess.env. This due to backwards compatibility issues with a deprecated API.注意,当在spawn过程中接收一个空对象,这会导致创建的进程使用空的环境变量而不是使用process.env.这是由于与一个废弃API向后兼容的问题.The stdio option tochild_process.spawn()is an array where each index corresponds to a fd in the child. The value is one of the following:child_process.spawn()中的stdio选项是一个数组,每个索引对应子进程中的一个文件标识符。可以是下列值之一:1. pipe- Create a pipe between the child process and the parent process. The parent end of the pipe is exposed to the parent as a property on thechild_processobject asChildProcess.stdiofd. Pipes created for fds 0 - 2 are also available as ChildProcess.stdin, ChildProcess.stdout and ChildProcess.stderr, respectively.2. ipc- Create an IPC channel for passing messages/file descriptors between parent and child. A ChildProcess may have at mostoneIPC stdio file descriptor. Setting this option enables the ChildProcess.send() method. If the child writes JSON messages to this file descriptor, then this will trigger ChildProcess.on(message). If the child is a Node.js program, then the presence of an IPC channel will enable process.send() and process.on(message).3. ignore- Do not set this file descriptor in the child. Note that Node will always open fd 0 - 2 for the processes it spawns. When any of these is ignored node will open/dev/nulland attach it to the childs fd.4. Streamobject - Share a readable or writable stream that refers to a tty, file, socket, or a pipe with the child process. The streams underlying file descriptor is duplicated in the child process to the fd that corresponds to the index in thestdioarray.5. Positive integer - The integer value is interpreted as a file descriptor that is is currently open in the parent process. It is shared with the child process, similar to howStreamobjects can be shared.6. null,undefined- Use default value. For stdio fds 0, 1 and 2 (in other words, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the default isignore.1.pipe-在子进程与父进程之间创建一个管道,管道的父进程端以child_process的属性的形式暴露给父进程,如ChildProcess.stdiofd。 为 文件标识(fds) 0 - 2 建立的管道也可以通过 ChildProcess.stdin,ChildProcess.stdout 及 ChildProcess.stderr 分别访问。2.3.ipc- 创建一个IPC通道以在父进程与子进程之间传递 消息/文件标识符。一个子进程只能有最多一个IPC stdio 文件标识。 设置该选项激活 ChildProcess.send() 方法。如果子进程向此文件标识符写JSON消息,则会触发 ChildProcess.on(message)。 如果子进程是一个nodejs程序,那么IPC通道的存在会激活process.send()和process.on(message)4.5.ignore- 不在子进程中设置该文件标识。注意,Node 总是会为其spawn的进程打开 文件标识(fd) 0 - 2。 当其中任意一项被 ignored,node 会打开/dev/null并将其附给子进程的文件标识(fd)。6.7.Stream对象 - 与子进程共享一个与tty,文件,socket,或者管道(pipe)相关的可读或可写流。 该流底层(underlying)的文件标识在子进程中被复制给stdio数组索引对应的文件标识(fd)8.9.正数 - 该整形值被解释为父进程中打开的文件标识符。他与子进程共享,和Stream被共享的方式相似。10.11.null,undefined- 使用默认值。 对于stdio fds 0,1,2(或者说stdin,stdout和stderr),pipe管道被建立。对于fd 3及往后,默认为ignore12.As a shorthand, thestdioargument may also be one of the following strings, rather than an array:作为快捷方式,stdio参数除了数组也可以是下列字符串之一: ignore-ignore, ignore, ignore pipe-pipe, pipe, pipeinherit-process.stdin, process.stdout, process.stderror0,1,2ignore-ignore, ignore, ignore pipe-pipe, pipe, pipe inherit-process.stdin, process.stdout, process.stderr或0,1,2Example:示例:/ 开启一个额外的 fd=4 来与提供 startd 风格接口的程序进行交互。 spawn(prg, , stdio: pipe, null, null, null, pipe );If thedetachedoption is set, the child process will be made the leader of a new process group. This makes it possible for the child to continue running after the parent exits.如果detached选项被设置,则子进程会被作为新进程组的 leader。这使得子进程可以在父进程退出后继续运行。By default, the parent will wait for the detached child to exit. To prevent the parent from waiting for a givenchild, use thechild.unref()method, and the parents event loop will not include the child in its reference count.缺省情况下,父进程会等待脱离了的子进程退出。要阻止父进程等待一个给出的子进程child,使用child.unref()方法,则父进程的事件循环引用计数中将不会包含这个子进程。Example of detaching a long-running process and redirecting its output to a file:脱离一个长时间运行的进程并将它的输出重定向到一个文件的例子: child.unref();When using thedetachedoption to start a long-running process, the process will not stay running in the background unless it is provided with astdioconfiguration that is not connected to the parent. If the parentsstdiois inherited, the child will remain attached to the controlling terminal.当使用detached选项来启动一个长时间运行的进程,该进程不会在后台保持运行,除非向它提供了一个不连接到父进程的stdio配置。如果继承了父进程的stdio,则子进程会继续附着在控制终端。There is a deprecated option calledcustomFdswhich allows one to specify specific file descriptors for the stdio of the child process. This API was not portable to all platforms and therefore removed. WithcustomFdsit was possible to hook up the new processstdin, stdout, stderrto existing streams;-1meant that a new stream should be created. Use at your own risk.有一个已废弃的选项customFds允许指定特定文件描述符作为子进程的 stdio。该 API 无法移植到所有平台,因此被移除。使用customFds可以将新进程的stdin, stdout, stderr钩到已有流上;-1表示创建新流。自己承担使用风险。See also:child_process.exec()andchild_process.fork()参阅:child_process.exec()和child_process.fork()child_process.exec(command, options, callback)# commandStringThe command to run, with space-separated arguments optionsObjecto cwdStringCurrent working directory of the child processo envObjectEnvironment key-value pairso encodingString(Default: utf8)o shellStringShell to execute the command with (Default: /bin/sh on UNIX, cmd.exe on Windows, The shell should understand the-cswitch on UNIX or/s /con Windows. On Windows, command line parsing should be compatible withcmd.exe.)o timeoutNumber(Default: 0)o maxBufferNumber(Default: 200*1024)o killSignalString(Default: SIGTERM) callbackFunctioncalled with the output when process terminateso errorErroro stdoutBuffero stderrBufferReturn: ChildProcess objectcommandString将要执行的命令,用空格分隔参数 optionsObjecto cwdString子进程的当前工作目录o envObject环境变量键值对o encodingString编码(缺省为 utf8)o shellString运行命令的 shell(UNIX 上缺省为 /bin/sh,Windows 上缺省为 cmd.exe。该 shell 在 UNIX 上应当接受-c开关,在 Windows 上应当接受/s /c开关。在 Windows 中,命令行解析应当兼容cmd.exe。)o timeoutNumber超时(缺省为 0)o maxBufferNumber最大缓冲(缺省为 200*1024)o killSignalString结束信号(缺省为 SIGTERM) callbackFunction进程结束时回调并带上输出o errorErroro stdoutBuffero stderrBuffer 返回:ChildProcess 对象Runs a command in a shell and buffers the output.在 shell 中执行一个命令并缓冲输出。child = exec(cat *.js bad_file | wc -l, function (error, stdout, stderr) console.log(stdout: + stdout); console.log(stderr: + stderr); if (error != null) console.log(exec error: + error); );The callback gets the arguments(error, stdout, stderr). On success,errorwill benull. On error,errorwill be an instance ofErroranderr.codewill be the exit code of the child process, anderr.signalwill be set to the signal that terminated the pr
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 【正版授权】 ISO/TS 16755-1:2025 EN Acoustics - Non-acoustic factors influencing the perception,interpretation and response to environmental sounds - Part 1: Definition and conceptual f
- 【正版授权】 ISO 24165-1:2025 EN Digital token identifier (DTI) - Registration,assignment and structure - Part 1: Method for registration and assignment
- 【正版授权】 ISO 80369-6:2025 EN Small bore connectors for liquids and gases in healthcare applications - Part 6: Connectors for neural applications
- 【正版授权】 ISO 80000-4:2019/Amd 1:2025 EN Quantities and units - Part 4: Mechanics - Amendment 1
- 【正版授权】 IEC 60079-19:2025 FR Explosive atmospheres - Part 19: Equipment repair,overhaul and reclamation
- 北汽知识培训集团课件
- 校园食堂食品安全知识培训课件
- 校园消防知识培训课件新闻稿
- 校园消防安全知识培训
- 物业人民调解员考试试题及答案
- 网约车停运损失赔偿协议书范文
- 移动宽带注销委托书模板需要a4纸
- 精细化600问考试(一)附有答案
- 超融合解决方案本
- 知识题库-人社练兵比武竞赛测试题及答案(八)
- SYT 0452-2021 石油天然气金属管道焊接工艺评定-PDF解密
- 《育婴师培训》-课件:环境消毒基础知识
- 关于规范村级财务管理的审计建议
- 长安欧尚A800说明书
- 火灾应急预案组织架构图
- 山东省济宁市第十五中学2023-2024学年(五四学制)六年级上学期第一次月考语文试题
评论
0/150
提交评论