简体   繁体   English

为什么我在nodejs中child_process的fork方法的相同代码的不同设备中得到不同的输出?

[英]why I'm getting different outputs in different devices of the same code of the child_process's fork method in nodejs?

Main I have two files, one is the parent file and another one is the child file. Main 我有两个文件,一个是父文件,另一个是子文件。 I tested in two different systems one mac os monastery and another one is dell - ubuntu 20., In both systems, I'm getting the different sequences of output(console log) as in below-attached pictures我在两个不同的系统中进行了测试,一个是 mac os monastery,另一个是 dell - ubuntu 20。在这两个系统中,我得到了不同的输出序列(控制台日志),如下图所示

app.js:应用程序.js:

var cp = require('child_process');



var child = cp.fork(__dirname + '/child.js');
  
child.on('message', function(m) {
  console.log('Parent process received:', m);
});
  
child.send({ hello: 'from parent process' });



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

child.js child.js

    process.on('message', function(m) {
      console.log('Child process received:', m);
    });
    
    process.send({ hello: 'from child process' });

Mac os montery: output: Mac os montery:输出:

Child process received: { hello: 'from parent process' }
Parent process received: { hello: 'from child process' }

Ubunt 20, output: Ubuntu 20,输出:

Parent process received: { hello: 'from child process' } 
Child process received: { hello: 'from parent process' }

Output links:输出链接:

Output: mac os monterey输出:mac os monterey

Output: Ubuntu 20输出:Ubuntu 20

When you fork a process, there are no guarantees about the order that the parent and child will next run in. Even if you see one consistent order on macOS and another on Ubuntu, this isn't guaranteed and you shouldn't rely on it.当你 fork 一个进程时,不能保证父进程和子进程下一次运行的顺序。即使你在 macOS 上看到一个一致的顺序,在 Ubuntu 上看到另一个,这并不能保证,你不应该依赖它. If you need things to happen in a certain order, then you need to structure your code differently to guarantee it (for example, you could have the child not send the message to the parent until it's in its own message received handler).如果您需要以某种顺序发生事情,那么您需要以不同的方式构造您的代码以保证它(例如,您可以让子级在它自己的消息接收处理程序中之前不将消息发送给父级)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM