简体   繁体   中英

How to resolve the error while executing top command using node child_process.exec?

I am trying to execute a bunch of bash commands using node.js. I used child_process.exec to execute the commands.

var child_process = require('child_process');
child_process.exec("ps -p $(lsof -ti tcp:8088) o pid=,comm=",function(err,stdout, stderr){
    if(err){
            console.log('error',err);
            return;
    }
    console.log('stdout', stdout);
});

This will list the process id running in the port 8088 along with name. In the similar way when i try to execute top command with a process id to check cpu and memory utilization. I am facing an error.

var execTop = function(pid){
        child_process.exec("top -p 12769", function(err, stdout, stderr){
                if(err){
                        console.log('error',err);
                        return;
                }
                console.log("top output",stdout);
        })
} 

I couldn't find much resource online to clarify this issue. The actual error is

error { [Error: Command failed: /bin/sh -c top -p 12769
top: failed tty get
]
  killed: false,
  code: 1,
  signal: null,
  cmd: '/bin/sh -c top -p 12769' }

I appreciate the possible solutions suggested. Thanks in advance.

If you really want to run top like this, you need to run in it "Batch Mode", like:

top -b -n 1 -p 12345

This is because top is usually meant to be an interactive command and wants to have an actual terminal to write to. You might want to consider using something like ps u -p 12345 for more concise output.

正如Grisha所建议的,请使用“批处理模式”,如果仅需要CPU和内存,则对于默认的顶部输出,我将使用类似以下内容:

top -b -n 1 -p 12345 | awk '{if(NR>7)print $9,$10}'

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