How to get Windowid from PID from a electron Application - linux

I want to get the WindowID from the PID of an Electron Process (for example riot-desktop)
I tried to get it with xdotools like this:
$ xdotool search --pid $(pgrep riot)
nothing is printed
$ pgrep riot
30461
$ xdotool search --pid 30461
nothing is printed again

You have to search for the pid of the subprocess of electron.
You can get the pid of the subprocess with:
PID=$(ps h -C electron | grep riot | cut -f1 -d"?")
now you can search for the pid
xdotool search --pid $PID
you can combine both commands to a single command
xdotool search --pid $(ps h -C electron | grep riot | grep witzerstorfer | cut -f1 -d"?")
if your ps returns multiple pid's you have to add more grep commands, for example if you work with profiles the command could look like this:
PID=$(ps h -C electron | grep riot | grep $PROFILENAME | cut -f1 -d"?")

If you want to find windowID of your electron application then you can use
win.getMediaSourceId()
Returns String - Window id in the format of DesktopCapturerSource's id. For example "window:1324:0".
More precisely the format is window:id:other_id where id is HWND on Windows, CGWindowID (uint64_t) on macOS and Window (unsigned long) on Linux. other_id is used to identify web contents (tabs) so within the same top level window.
Example:
// In the main process.
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ width: 800, height: 600 })
// Load a remote URL
win.loadURL('https://github.com')
// Or load a local HTML file
win.loadURL(`file://${__dirname}/app/index.html`)
// Print window id
console.log('window id is', win.getMediaSourceId())

Related

prstat in Ubuntu or Centos

As the Java Performance said:
Solaris prstat has additional capabilities
such as reporting both user and kernel or system CPU utilization along with other
microstate information using the prstat -m and -L options. The -m option prints
microstate information, and -L prints statistics on per lightweight process.
There is any tool available like prstat in Centos or Ubuntu ?
I believe the Linux commands you are looking for are top and pstree .
Here is ptree for Linux,
#!/bin/sh
# Solaris style ptree
[ -x /usr/bin/ptree ] && exec /usr/bin/ptree "$#"
# Print process tree
# $1 = PID : extract tree for this process
# $1 = user : filter for this (existing) user
# $1 = user $2 = PID : do both
PATH=/bin:/usr/bin:/usr/sbin:/sbin
export PATH
psopt="-e"
case $1 in
[a-z]*) psopt="-u $1";shift;;
esac
[ -z "$1" ] &&
exec ps $psopt -Ho pid=,args=
#some effort to add less to the ps list
tmp=/tmp/ptree.$$
trap 'rm $tmp' 0 HUP INT TERM
ps $psopt -Ho pid=,args= >$tmp
<$tmp awk '
{ ci=index(substr($0,7),$2); o[ci]=$0 }
ci>s[a] { s[++a]=ci }
$1==pid {
for(i=1;i<=a;i++) {
si=s[i]; if(si<=ci) print o[si]
}
walkdown=ci
next
}
ci<walkdown { exit }
walkdown!=0 { print }
' pid="$1"
There is no prstat "equivalent" tool in Linux. You can use a combination of top and ps (or /proc/$pid/ resources) to get some useful result; maybe writing a shell script (using grep, sed and awk) which collects results from above commands and files.
Just for reference I found this link about top command and kernel, user and idle CPU utilization intresting
http://blog.scoutapp.com/articles/2015/02/24/understanding-linuxs-cpu-stats
Hope this helps.

Get a variable from an array in perl

I am running a following command and getting the 4 lines as output.
userid#server:/home/userid# ps -ef|grep process
This is the output for the command.
userid 10117 9931 0 06:25 pts/0 00:00:00 grep process
userid 15329 1 0 Jul11 ? 00:03:40 process APP1
userid 15334 15329 1 Jul11 ? 2-00:40:53 process1 APP1
userid 15390 15334 0 Jul11 ? 05:19:31 process2 APP1
I want to save the value APP1 to a variable using perl. So I want an output like $APP = APP1.
Try this (your output is in this case in the file in.txt):
perl -ne ' /(APP\d+)/g; print "$1\n";' in.txt
Prints:
APP1
APP1
APP1
Perhaps using an array for the captured APPS1s would be helpful:
use strict;
use warnings;
my #apps;
while (<DATA>) {
push #apps, $1 if /process\d*\s+(.+)/;
}
print "$_\n" for #apps;
__DATA__
userid 10117 9931 0 06:25 pts/0 00:00:00 grep process
userid 15329 1 0 Jul11 ? 00:03:40 process APP1
userid 15334 15329 1 Jul11 ? 2-00:40:53 process1 APP1
userid 15390 15334 0 Jul11 ? 05:19:31 process2 APP1
Output:
APP1
APP1
APP1
Is APP1 the last entry on the command line? Or, is it the second word after the process* command?
If it's the last word on the line, you could use this:
use strict;
use warnings;
use autodie;
open my $command_output, "|-", "pgrep -fl process";
while ( my $command = < $command_output > ) {
$command =~ /(\w+)$/;
my $app = $1; #The last word on the line...
Otherwise, things get a bit more tricky. I am using pgrep instead of ps -ef | grep. The ps command returns a header, plus lots of fields. You need to split them, and parse them all. Plus, it even shows you the grep command you used to get the processes you're interested in.
The pgrep command with the -f and -l parameters returns no header and returns just the process ID followed by the full command. This makes it much easier to parse with a regular expression. (If you don't know about regular expressions, you need to learn about them.)
open my $command_output, "|-", "pgrep -fl process";
while ( my $command = < $command_output > ) {
if ( not $process =~ /^\d+\s+process\w+\s+(\w+)/ ) {
next;
}
my $app = $1; #The second word in the returned command...
There's no need to split or mess. There's no header to skip The regular expression matches the numeric process ID, the process command, and then selects the second word. I even check to make sure the output of the pgrep matches what I expect. Otherwise, I'll get the next line.
I used a single line command to get the required result.
#!/usr/bin/perl
use strict;
use warnings;
my $app1
$app1 = ( split /\s+/, `pgrep -f process1` )[-1];
print ($app1);

Getting the Process ID of another program in Groovy using 'command slinging'

import java.lang.management.*
final String name = ManagementFactory.getRuntimeMXBean().getName();
final Integer pid = Integer.parseInt(name[0..name.indexOf("#")-1])
I tried this in my code but that gets the pid of the running program. I am running a sleeping script (all it does is sleep) called sleep.sh and i want to get the pid of that. Is there a way to do that? I have not found a very good way myself.
I also used a ps | grep and i can see the process id is there a way to output it though?
Process proc1 = 'ps -ef'.execute()
Process proc2 = 'grep sleep.sh'.execute()
Process proc3 = 'grep -v grep'.execute()
all = proc1 | proc2 | proc3
is there a way i can modify the all.text to get the process id or is there another way to get it?
Object getNumber(String searchProc) {
//adds the process in the method call to the grep command
searchString = "grep "+searchProc
// initializes the command and pipes them together
Process proc1 = 'ps -ef'.execute()
Process proc2 = searchString.execute()
Process proc3 = 'grep -v grep'.execute()
all = proc1 | proc2 | proc3
//sets the output to the piped commands to a string
output = all.text
//trims down the string to just the process ID
pid = output.substring(output.indexOf(' '), output.size()).trim()
pid = pid.substring(0, pid.indexOf(' ')).trim()
return pid
}
This is my solution. (I wanted to make it a method so i put the method declaration at the very top)
My problem at the beginning was that there was more spaces than one between the process name and the pid. but then i found the trim method and that worked nicely. If you have questions on my method let me know. I will check back periodically.

How to get all parent processes and all subprocesses with `pstree`

Command pstree PID can show all subprocess information of the process specified by PID. However, I also want to know all parent process information of the process PID, how can I get it?
An example:
init
|- parent_process
| `- current_process
| |- subprocess_1
| `- subprocess_2
`- other_process
What I want is when I run pstree current_process_pid, I want to get below output:
init
`- parent_process
`- current_process
|- subprocess_1
`- subprocess_2
When I run pstree subprocess_1_pid, it will output:
init
`- parent_process
`- current_process
`- subprocess_1
# With my psmisc 22.20:
pstree -p -s PID
Maybe if with ps -ef:
awk -vPID=$1 '
function getParent ( pid ) {
if (pid == "" || pid == "0") return;
while ("ps -ef | grep "pid | getline) {
if ($2 == pid) {
print $8"("$2") Called By "$3;
getParent($3);
break;
}
}
close ("ps -ef")
}
BEGIN { getParent(PID) }
'
This is ugly assuming ps output column and order. Actually one single run of ps -ef contains all info needed.
This don't worth the time, I still recommend updating psmisc, it won't hurt.
EDIT: A mimic using single run ps -ef:
ps -ef | awk -vPID=$1 '
function getpp ( pid, pcmd, proc ) {
for ( p in pcmd ) {
if (p == pid) {
getpp(proc[p], pcmd, proc);
if (pid != PID) printf("%s(%s)───", pcmd[pid], pid);
}
}
}
NR > 1 {
# pid=>cmd
pcmd[$2] = $8;
# pid=>Parent
pproc[$2] = $3;
}
END {
getpp(PID, pcmd, pproc);
printf "\n";
system("pstree -p "PID);
}'
I found laps options mentioned by #haridsv (pstree -laps <pid>) being a solution. It was a bit verbose for me though, so I'd stick to a shorter aps output.
To get the process tree of the current process (its ID is $$ in Bash):
pstree -aps $$
That prints the process tree like this:
systemd,1
└─kitty,86739
└─bash,86742
└─pstree,86904 -aps 86742

How to query X11 display resolution?

It seems like an simple problem, but I can't find the answer: How do you query (via X11) what monitors exist and their resolutions?
Check out display macros and screen macros from the Xlib manual.
Specifically:
From the first link: ScreenCount(), ScreenOfDisplay()
From the second link: WidthOfScreen(), HeightOfScreen()
This might be helpfull for cli and scripting
xwininfo -root
But xRandR might be more accurate, especially, when there is multiple monitor environment:
xrandr
If Xinerama is in use, try XineramaQueryScreens. Otherwise, you may be able to assume a single screen and use (X)WidthOfScreen/(X)HeightOfScreen.
(Also see the other answer. It's remotely possible someone is using the old X screen model where your screens are :x.0, :x.1, etc.)
For modern X servers, there's also the XRandR extension, which provides the most up-to-date model of multi screen layout information, including overlapping screens and dynamic screen changes.
Documentation of it is available in the XRandR 1.3.1 Protocol spec and the libXrandr man page.
The library X11 working only with unix-like OS, so it is a not cross-platform solution.
A full code
#include <stdio.h>
#include <X11/Xlib.h>
int
main(const int argc, const char *argv[])
{
Display *display;
Screen *screen;
// open a display
display = XOpenDisplay(NULL);
// return the number of available screens
int count_screens = ScreenCount(display);
printf("Total count screens: %d\n", count_screens);
for (int i = 0; i < count_screens; ++i) {
screen = ScreenOfDisplay(display, i);
printf("\tScreen %d: %dX%d\n", i + 1, screen->width, screen->height);
}
// close the display
XCloseDisplay(display);
return 0;
}
A compilation
gcc -o setup setup.c -std=c11 `pkg-config --cflags --libs x11`
A result (actual for my computer)
Total count screens: 1
Screen 1: 1366X768
Based on:
https://tronche.com/gui/x/xlib/display/opening.html
https://tronche.com/gui/x/xlib/display/display-macros.html
https://tronche.com/gui/x/xlib/display/screen-information.html
https://stackoverflow.com/a/1829747/6003870
Python
import os
from Xlib import X, display
d = display.Display()
s = d.screen().root
output = os.popen("xrandr --listmonitors | grep '*' | awk {'print $4'}").read().splitlines()
num_sc = s.xinerama_get_screen_count().screen_count
width = s.get_geometry().width
height = s.get_geometry().height
print("Total count screens: %s" % num_sc)
for i in range(num_sc):
print("\tScreen %s(%s): %sX%s" % (i, output[i], width, height))
Bash
$ xrandr --listmonitors
$ xrandr
$ xrandr | grep '*' | awk {'print $1'}
Clean xrandr output for imagemagick use
$ xrandr |grep \* |awk '{print $1}'
Results here in:
1920x1080
The program xdpyinfo tells you almost everything about your X11 server.
$ xdpyinfo | sed -n '/^screen #0/{n;p}'
dimensions: 3840x2160 pixels (696x391 millimeters)
For ffmpeg:
$ xdpyinfo | sed -n '/^screen #0/{n;s/^[ a-z:]*//;s/ .*//p}'
3840x2160

Resources