首页 > 解决方案 > x 秒后终止 childprocess.exec

问题描述

我找不到像子进程等待时间或响应等待时间这样的东西,因为我需要这样的东西。所以希望有人可以在这里帮助我......

如果您看到下面的代码,我正在打印 ros 主题。但是这个话题还活着,但没有返回任何东西。所以如果它在 1-2 秒内没有收到任何东西,我怎么能终止/杀死这个子进程。因为这正在吞噬我的记忆

result = await execute("rostopic echo -n1 --noarr --offset /odom");


function execute(command) {
    return new Promise(function(resolve, reject) {
        childProcess.exec(command, function(error, standardOutput, standardError) {
            if (error) {
                reject(error)
            }
            if (standardError) {
                reject(standardError)
            }
            resolve(standardOutput);
        });
    }).catch((e) => {logger.crit(FOCNO+"-"+e)});
}

标签: javascriptnode.jsroschild-process

解决方案


const x = 3 /*seconds*/ * 1000;

function execute(command) {
    return new Promise(function(resolve, reject) {
        command = command.split(' ');
        const ps = childProcess.spawn(command[0], command.slice(1));
        const killTimeout = setTimeout(() => ps.kill(), x);

        ps.stdout.on('data', data => {
            clearTimeout(killTimeout);
            resolve(data);
        });

        ps.stderr.on('data', data => reject(data));
    }).catch((e) => {logger.crit(FOCNO+"-"+e)});
}

result = await execute("rostopic echo -n1 --noarr --offset /odom");

推荐阅读