Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@ target
**/*~
**/node_modules
**/.DS_Store
index.d.ts

9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,15 @@ id, and sends a `CTRL-C` event to that console.

> Note: This is a no-op on non-windows platforms

## API

### `ctrlc(pid, processKillerPath?)`

Arguments:

* **pid** pid of process to kill
* **processKillerPath** (optional) path to `process-killer.exe` if it is not at the default location. Normally `process-killer.exe` should be located in the `ctrlc-windows` module, but if you're using a bundler like `rspack` and also using `node-loader` then you'll have to manually copy `ctrlc-windows/dist/{x64,arm64}/process-killer.exe` into your app bundle and provide that path here.

## Usage

``` javascript
Expand Down
6 changes: 0 additions & 6 deletions index.d.ts

This file was deleted.

2 changes: 1 addition & 1 deletion lib/index.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export function ctrlc(pid: number): void;
export function ctrlc(pid: number, processKillerPath?: string): void;
37 changes: 29 additions & 8 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,41 @@
const { execFileSync } = require("child_process");
const { platform, arch } = require("os");
const { join } = require("path");

const archDistDirName = arch() === "arm64" ? "arm64" : "x64";
const isArm64 = arch() === "arm64"; // ? "arm64" : "x64";
const archDistDirName = isArm64 ? "arm64" : "x64";
const isWindows = platform() === "win32";

const native =
platform() === "win32"
? require(`../dist/${archDistDirName}/ctrlc-windows.node`)
: require("./posix");
// this would be more friendly to bundlers
const native = isWindows
? isArm64
? require("../dist/arm64/ctrlc-windows.node")
: require("../dist/x64/ctrlc-windows.node")
: null;
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bundlers like webpack or rspack won't be able to parse non literal paths in require.


/**
* workaround for node-loader users; because node-loader only copies .node files,
* devs using them will need to manually copy process-killer.exe into their app bundle
* and provide the path to it when calling ctrlc()
*/
const defaultKillerPath = join(__dirname, "..", `dist/${archDistDirName}/process-killer.exe`);

module.exports = {
ctrlc(pid) {
ctrlc(pid, processKillerPath = defaultKillerPath) {
if (!isWindows) {
let error = new Error(
"tried to invoke windows-specific ctrlc on a non-windows platform",
);
error.name = "PlatformError";
throw error;
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

move posix.js here

}
try {
// don't even attempt if the
// process is not running
if (process.kill(pid, 0)) {
const processKillerPath = join(__dirname, "..", `dist/${archDistDirName}/process-killer.exe`);
native.ctrlc(pid, processKillerPath);
native.ignoreSignal(true);
execFileSync(processKillerPath, [pid.toString()]);
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

native.ignoreSignal(false);
}
} catch (error) {
if (error.code !== "ESRCH") {
Expand All @@ -24,3 +44,4 @@ module.exports = {
}
},
};

7 changes: 0 additions & 7 deletions lib/posix.js

This file was deleted.

6 changes: 3 additions & 3 deletions src/bin/process-killer.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
#![windows_subsystem = "windows"]

#[cfg(windows)]
use std::error::Error;

#[cfg(windows)]
use windows::Win32::System::Console::{
AttachConsole, FreeConsole, GenerateConsoleCtrlEvent, SetConsoleCtrlHandler, CTRL_C_EVENT,
AttachConsole, GenerateConsoleCtrlEvent, SetConsoleCtrlHandler, CTRL_C_EVENT,
};

#[cfg(windows)]
Expand All @@ -21,8 +23,6 @@ pub fn main() -> Result<(), Box<dyn Error>> {
#[cfg(windows)]
fn kill_pid(pid: u32) -> Result<(), Box<dyn Error>> {
unsafe {
FreeConsole();
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

a subsystem:windows program doesn't have a console to begin with


if AttachConsole(pid).as_bool() {
SetConsoleCtrlHandler(None, true);
GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0);
Expand Down
49 changes: 2 additions & 47 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,56 +3,11 @@
#[macro_use]
extern crate napi_derive;

use napi::{Error, JsNumber, JsString, Result, Status};
use std::ffi::OsString;
use std::process::Command;
use windows::Win32::System::Console::SetConsoleCtrlHandler;

#[napi]
fn ctrlc(pid_from_js: JsNumber, killer_exe_path: JsString) -> Result<bool> {
let pid = match pid_from_js.get_int32() {
Ok(child) => child,
Err(error) => {
return Err(napi::Error {
status: Status::GenericFailure,
reason: format!("unable to parse passed pid: {}", error),
});
}
};
let killer_exe = match OsString::try_from(killer_exe_path.into_utf8()?.into_owned()?) {
Ok(child) => child,
Err(error) => {
return Err(napi::Error {
status: Status::GenericFailure,
reason: format!("unable to kind process killer executable: {}", error),
});
}
};

fn ignore_signal(ignore: bool) {
unsafe {
SetConsoleCtrlHandler(None, true);
};

let mut killer = match Command::new(killer_exe).arg(format!("{:?}", pid)).spawn() {
Ok(child) => child,
Err(error) => {
return Err(napi::Error {
status: Status::GenericFailure,
reason: format!("unable to spawn process to kill pid: {}", error),
});
}
};

let status = killer.wait();

unsafe { SetConsoleCtrlHandler(None, false) };

match status {
Ok(status) if status.success() => Ok(true),
Ok(_) => Err(Error::new(
Status::GenericFailure,
format!("unable to kill process with pid '{:?}'", pid),
)),
Err(error) => Err(Error::new(Status::GenericFailure, format!("{}", error))),
SetConsoleCtrlHandler(None, ignore);
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the only thing that we can't do in nodejs

}
}
Loading