如何以可编程方式等待进程启动端点

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何以可编程方式等待进程启动端点相关的知识,希望对你有一定的参考价值。

我在node.js中创建了一个带有单元测试和验收测试的small example application

单元和验收测试都在mocha过程中运行。验收测试从分叉过程开始,基本上在before()方法上运行服务器。 after()方法停止进程和

before((initialized) => {
  console.log('before script');
  serverProcess = child_process.fork('server.js');
  serverProcess.on('close', function (code) {  
  console.log('child process exited with code ' + code);  
});
setTimeout(() => {
  console.log('1s elapsed');
  initialized();
}, 1000);

没有任何延迟的代码在我的本地gitlab-runner上运行,但是在服务器上并不总是这样,所以我增加了延迟 - 等待一段时间直到服务器启动。根据经验,我发现1s就够了,而.5s则不行。但是,我想知道我该怎么做以确保服务器是。

Are there any solutions to run server, execute the tests and shutdown the server that works on Linux, Windows, docker and outside of it?
答案

how to communicate between fork processes有很好的帮助。

这个想法是从孩子那里发来一条消息说给他爸爸(我准备好了!)。然后爸爸会继续工作。

示例:

before((initialized) => {
  serverProcess = child_process.fork('server.js');

  serverProcess.on('close', function(code) {
    console.log('child process exited with code ' + code);
  });

  serverProcess.on('close', function(code) {
    console.log('child process exited with code ' + code);
  });

  // We add a backup plan. If it takes too long to launch, throw
  const timeout = setTimeout(() => {
    initialized(new Error('tiemout');
  }, 30000);

  // Cait for the child to send a message to us
  serverProcess.on('message', function(str) {
    if (str === 'init done') {
      clearTimeout(timeout);

      // server.js got successfully initialized
      initialized();
    }
  });
});

// To add inside of your server.js listen
if (process.send) {
  process.send("init done");
}

以上是关于如何以可编程方式等待进程启动端点的主要内容,如果未能解决你的问题,请参考以下文章

如何以编程方式更改端点的身份配置?

如何以编程方式编写端点(netPeer Tcp 绑定)

linux打开终端如何启动scala,如何在终端下运行Scala代码片段?

如何以编程方式修改 WCF app.config 端点地址设置?

Visual Studio - 以编程方式将调试器附加到远程进程

如何以编程方式发现我的 c# 应用程序的当前端点?