通过Node.js子进程关闭CS:GO专用服务器

Turn off CS:GO Dedicated Server via Node.js child_process

本文关键字:GO 专用 服务器 CS Node js 子进程 通过      更新时间:2023-09-26



我一直在尝试以编程方式控制多个Counter Strike:Global Offensive专用服务器。一切都很好,但我很难完全关闭它。当你打开服务器时,它会创建两个进程:srcds_runsrcds_linux。我可以很容易地执行child_process.kill(),它会关闭srcds_run进程,但srcds_linux进程仍在运行,即使服务器关闭。如果我试图杀死所有srcds_linux进程,那么它会杀死的所有CSGO服务器,即使我只想关闭一个。有没有办法选择相应的srcds_runsrcds_linux进程?

这是我迄今为止的代码:

// Turns on the server if not already on
Server.prototype.start = function(callback) {
    if(!this.online) {
        // Turn server on
        console.log('Starting server');
        this.process = spawn(this.directory + '/srcds_run', ['-game csgo', '-console', '-usercon', '+game_type 0', '+game_mode 0', '+mapgroup mg_active', '+map de_dust2', '+sv_setsteamaccount ' + this.token], { cwd: this.directory});
        this.process.stderr.on('data', function(err) {
            console.log('Error: ' + err);
        });
        this.process.stdin.on('data', function(chunk) {
            console.log('stdin: ' + chunk);
        });
        this.process.stdout.on('data', function(chunk) {
            console.log('stdout: ' + chunk);
        });
    }
    this.online = true;
    callback();
}
// Turns off the server if not already off
Server.prototype.stop = function(callback) {
    if(this.online) {
        // Turn server off
        console.log('Stopping server');
        this.process.kill();
    }
    this.online = false;
    callback();
}

我使用的是Ubuntu服务器,在node.js上使用child_process.spawn模块
我感谢您的帮助:)

因此,多亏了@dvlsg,我使用pgrep关闭了相应的srcds_linux进程。这是我目前掌握的代码。

var child_process = require('child_process');
var exec = child_process.exec;
function execute(command, callback){
    exec(command, function(error, stdout, stderr) {
        callback(stdout, error, stderr);
    });
};

// Turns off the server if not already off
Server.prototype.stop = function(callback) {
    if(this.online) {
        // Turn server off
        console.log('Stopping server');
        var processId = this.process.pid;
        execute('pgrep -P ' + processId, function(childId, error, stderror) {
            console.log('Parent ID: ' + processId);
            console.log('Child  ID: ' + childId);
            this.process.on('exit', function(code, signal) {
                console.log('Recieved event exit');
                execute('kill ' + childId);
                this.online = false;
                callback();
            });
            this.process.kill();
        });
    } else {
        this.online = false;
        callback();
    }
}

如果我改进了代码,我会更新它,但这就是我迄今为止所拥有的。