[bugfix] fix issue with reading processes in os.helpers.ts in linux

This commit is contained in:
silentrald
2024-12-05 08:48:04 +08:00
parent 127a538509
commit 78fb06fc63
2 changed files with 30 additions and 9 deletions
+8 -2
View File
@@ -196,8 +196,14 @@ ifDescribe(IS_LINUX)("Test os.helpers isProcessRunning", () => {
const running = await isProcessRunning(`bs-manager-${crypto.randomUUID()}`);
expect(running).toBe(false);
// No errors received
expect(logSpy).toHaveBeenCalledTimes(0);
// Throws because grep couldn't find any process with that name
expect(logSpy).toHaveBeenCalledTimes(1);
});
it("Empty process name", async () => {
const running = await isProcessRunning("");
expect(running).toBe(false);
expect(logSpy).toHaveBeenCalledTimes(0);
})
});
+22 -7
View File
@@ -3,9 +3,6 @@ import log from "electron-log";
import psList from "ps-list";
import { IS_FLATPAK } from "main/constants";
// There are 2 erroneous lines ps | grep which is both the ps and grep calls themselves
const MIN_PROCESS_COUNT_LINUX = 2;
type LinuxOptions = {
// Add the prefix to the command
// eg. command - "./Beat Saber.exe" --no-yeet, prefix - "path/to/proton" run
@@ -101,14 +98,24 @@ export function bsmExec(command: string, options?: BsmExecOptions): Promise<{
});
}
// Transform command from "steam" to "[s]team"
// NOTE: Can add an option to isProcessRunning/getProcessId to ignore this transformation
// in the future if needed
const transformProcessNameForPS = (name: string) => `[${name.at(0)}]${name.substring(1)}`;
async function isProcessRunningLinux(name: string): Promise<boolean> {
if (!name) {
return false;
}
try {
const { stdout: count } = await bsmExec(`ps awwxo args | grep -c "${name}"`, {
const processName = transformProcessNameForPS(name);
const { stdout: count } = await bsmExec(`ps awwxo args | grep -c "${processName}"`, {
log: true,
flatpak: { host: IS_FLATPAK },
});
return +count.trim() > MIN_PROCESS_COUNT_LINUX;
return +count.trim() > 0;
} catch(error) {
log.error(error);
return false;
@@ -143,14 +150,22 @@ async function isProcessRunningWindows(name: string): Promise<boolean> {
}
async function getProcessIdLinux(name: string): Promise<number | null> {
if (!name) {
return null;
}
try {
const { stdout } = await bsmExec(`ps awwxo pid,args | grep "${name}"`, {
const processName = transformProcessNameForPS(name);
const { stdout } = await bsmExec(`ps awwxo pid,args | grep "${processName}"`, {
log: true,
flatpak: { host: IS_FLATPAK },
});
if (!stdout) {
return null;
}
const line = stdout.split("\n")
.slice(0, -MIN_PROCESS_COUNT_LINUX)
.map(line => line.trimStart())
.find(line => line.includes(name) && !line.includes("grep"));
return line ? +line.split(" ").at(0) : null;