Skip to content

Commit

Permalink
Make the memory detection more resistant to locale issues
Browse files Browse the repository at this point in the history
- Certain non-english characters aren't considered "Word characters" in
  Regex, so \S (any non-whitespace) is now accepted
- The `free` command is ran with `LANG=C` to force English output even
  on non-english systems
- If the match fails for any other reason, we simply return 0 bytes
  total/used (which is at least a valid number, even if it doesn't make
  sense)
  • Loading branch information
CommandMC committed Sep 23, 2023
1 parent 917560b commit d5eac45
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 5 deletions.
3 changes: 2 additions & 1 deletion src/backend/utils/os/processes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { ChildProcess, spawn } from 'child_process'
type SpawnWrapperOptions = Partial<{
onStdout: (data: string, child: ChildProcess) => unknown
onStderr: (data: string, child: ChildProcess) => unknown
env: Record<string, string | undefined>
}>

interface SpawnWrapperReturn {
Expand All @@ -17,7 +18,7 @@ async function genericSpawnWrapper(
args: string[] = [],
options: SpawnWrapperOptions = {}
): Promise<SpawnWrapperReturn> {
const child = spawn(command, args)
const child = spawn(command, args, { env: options?.env })
child.stdout.setEncoding('utf-8')
child.stderr.setEncoding('utf-8')

Expand Down
10 changes: 6 additions & 4 deletions src/backend/utils/systeminfo/memory/linux.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ import type { PartialMemoryInfo } from './index'
import { genericSpawnWrapper } from '../../os/processes'

async function getMemoryInfo_linux(): Promise<PartialMemoryInfo> {
const { stdout } = await genericSpawnWrapper('free', ['-b'])
const match = stdout.match(/^\w*:\s*(\d*)\s*(\d*)/m)
const { stdout } = await genericSpawnWrapper('free', ['-b'], {
env: { ...process.env, LANG: 'C' }
})
const match = stdout.match(/^\S*:\s*(\d*)\s*(\d*)/m)
const totalString = match?.[1]
const usedString = match?.[2]
return {
total: Number(totalString),
used: Number(usedString)
total: totalString ? Number(totalString) : 0,
used: usedString ? Number(usedString) : 0
}
}

Expand Down

0 comments on commit d5eac45

Please sign in to comment.