简体   繁体   中英

kill child process exec

I need your help. I want to get the public IP address of my Beaglebone via ifconfig.me.

If I have an existing internet connection it works fine. If I don't have an internet connection the request should be aborted. Here is my code:

function publicIP_www(callback){
  try{
     exec('curl ifconfig.me',{timeout:3000}, function(error, stdout, stderr){ 
     callback(stdout); }); 
  } 
  catch (err){
     callback("000.000.000.000");
  }
}

The returned IP address is then displayed on a web site in the browser. If there is no internet connection, the browser calculates forever. It seems as if the call exec ...... is not terminated.

I'm looking forward to your support and hope that someone can tell me what I'm doing wrong.

best regards Hans

It's difficult to predict why it is in your case not working, due to not to be able see your code. But you can try next that works fine. Of Course it's dirty, just is an example.

Next code is for index.js file of the "Node.js Express App + Jade" project that was created from template in WebStorm IDE.

const util = require('util');
const exec = util.promisify(require('child_process').exec);

....
....

router.get('/', async function(req, res, next) {
  try {
    const {stdout, stderr} = await exec('curl ifconfig.me');
    res.render('index', { title: stdout});
  }
  catch (err) {
    res.render('index',{ title: "000.000.000.000"});
  }
});

OR use

const util = require('util');
const exec = require('child_process').exec;

function publicIP_www(callback){
  exec('curl ifconfig.me',{timeout:3000}, function(error, stdout, stderr){
    if (error) {
      return callback("000.000.000.000");
    }
    callback(stdout);
  });
}


router.get('/', function(req, res, next) {
  publicIP_www((title) => {
    res.render('index', { title });
  })
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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