HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Keep NumLock always on in Linux

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
numlockkeepalwayslinux

Problem

Intention

I intend to replace my own Bash script executing the following commands indefinitely in favor of this C++ compiled code, the reason being that the Bash script seemed very CPU ineffective.

It's not that I would think this solution is effective, nor perfect, but better than the one written in Bash for there is a great overhead over time.

The two commands are very simple:

-
/usr/bin/numlockx on

-
sleep 1

Environment

Linux Mint 18 with Cinnamon desktop environment.

Purpose

As I don't have a Num Lock indicator on my laptop, I want to ensure the Num Lock is always turned on.

xmodmap

I have tried using this utility, but it literally, excuse my wording, crippled my key mappings, which I have set up from inside Cinnamon DE.

Current C++ code

#include   // in order to use system function
#include  // in order to use sleep  function

int main()
{

do {

    system("/usr/bin/numlockx on");

    sleep(1);

} while (true);

return 0;

}


This is compiled with g++ 5.x as follows:

g++ numlock-always-on.c -o "numlock-always-on"

Solution

I don't know much C++, but your indentation isn't great. To fix this you could try running your code through a C/C++ linter.

Your code is also having a much larger performance hit than if you told your Xorg to do this. Assuming that you only want this to work in Xorg, rather than in both the console and Xorg, you can use setxkbmap as described in the Arch wiki page Keyboard configuration in Xorg. setxkbmap comes with a couple of options to change how your keyboard works, listed under /usr/share/X11/xkb/rules/base.lst. From this list numpad:mac looks like what you want, and will change your keyboard to always use numbers whether numlock is on or not.

And so I would use:

setxkbmap -option numpad:mac

Code Snippets

setxkbmap -option numpad:mac

Context

StackExchange Code Review Q#147810, answer score: 7

Revisions (0)

No revisions yet.