I am trying to find the version of java used by user when launching a program, there are multiple versions of java available in few systems, and JAVA_HOME is not consistently and reliably set.
i am trying to read the unit file of the service/program and parse the path and check the version of java.
ExecStart=/usr/bin/java -d64 -Xms512m -Xmx6g -cp
ExecStart = /usr/bin/java -jar
Is there a regex I can use for the purpose? What's an alternate/better approach?
Instead of parsing the service file, inspect the running service's state.
If you have a running process, you can do a lookup from /proc to find out what executables it has open; there's no reason to parse the service file.
findServiceExe() {
local svc pid retval=0 # avoid polluting namespace
for svc; do
pid=$(systemctl show "$svc" | awk -F= '$1 == "ExecMainPID" { print $2 }')
if [[ $pid ]] && kill -0 "$pid"; then
readlink -f "/proc/$pid/exe" || (( retval |= $? ))
else
echo "No actively-running process found for service $svc" >&2; retval=1
fi
done
return "$retval"
}
...after which you can use the function like so:
$ findServiceExe myJavaService
/usr/lib/jvm/java-8-openjdk/jre/bin/java
This is a much better practice, because the service file itself is not enough information; you need to read all the various overlay files, EnvironmentFiles, etc., to fully understand the context of the process it invokes.
Related
Below Bash script lists serial port along with USB device friendly name. I'd like to do exact same thing but in C++ and without using dependency like libusb.
#!/bin/bash
for sysdevpath in $(find /sys/bus/usb/devices/usb*/ -name dev); do
(
syspath="${sysdevpath%/dev}"
devname="$(udevadm info -q name -p $syspath)"
[[ "$devname" == "bus/"* ]] && continue
eval "$(udevadm info -q property --export -p $syspath)"
[[ -z "$ID_SERIAL" ]] && continue
echo "/dev/$devname "$ID_SERIAL""
)
done
I have encountered other C/C++ code that use various APIs but none was able to get friendly name and /dev/ttyPort like above script. For example, output of above script is:
/dev/input/event13 Razer_Razer_Mamba_Tournament_Edition
/dev/input/event14 Razer_Razer_Mamba_Tournament_Edition
/dev/input/mouse0 Razer_Razer_Mamba_Tournament_Edition
/dev/input/event4 Razer_Razer_Mamba_Tournament_Edition
/dev/video0 Chicony_Electronics_Co._Ltd._Integrated_Camera_0001
/dev/input/event10 Chicony_Electronics_Co._Ltd._Integrated_Camera_0001
/dev/ttyACM0 3D_Robotics_PX4_FMU_v2.x_0
I'm developing a C++ library that has a piece of shell script code that return the name of a specific serial port. When I run this script in console either X64 desktop or Arm enviorment the script returns the right answer. My problem ocur when I execute the same script inside of the library, the returns shows bad formed string like ÈÛT¶ÈÛT¶¨a , but the expected is /dev/ttyACM0.
The script that run inside of library:
Script
bash -c 'for sysdevpath in $(find /sys/bus/usb/devices/usb*/ -name dev);do(syspath="${sysdevpath%/dev}";devname="$(udevadm info -q name -p $syspath)";[[ "$devname" == "bus/"* ]]&& continue;teste="$(udevadm info -q property --export -p $syspath | grep -i "company_name")";if [[ ! -z "${teste// }" && $devname == *"ttyACM"* ]]; then echo "/dev/$devname";fi);done;' 2> /dev/null
The following piece of code is used to save the content returned by the script into a file.
code c++
pfFile = fopen(CONFIG_FILE, "w+");
fwrite(result,strlen(result), 1, pfFile);
fclose(pfFile);
return 0;
Besides you didn't include what is result and where it comes from in your C++ code; you selected the hardest way to do this. Code running shell scripts inside a library most likely cause nothing but headaches.
Basically you can create an udev rule for your device to create an unique and stable file in /dev to access it. You can create one like this one in the ArchWiki
KERNEL=="video[0-9]*", SUBSYSTEM=="video4linux", SUBSYSTEMS=="usb", ATTRS{idVendor}=="05a9", ATTRS{idProduct}=="4519", SYMLINK+="video-cam1"
I'm writing a daemon that will log in to other machines to confirm that a service is running and also start, stop, or kill it. Because of this, the unix commands get a little long and obfuscated.
The basic shape of the commands that are forming are like:
bash -c 'ssh -p 22 user#host.domain.com pgrep -fl "APP.*APP_id=12345"'
Where APP is the name of the remote executable and APP_id is a parameter passed to the application when started.
The executable running on the remote side will be started with something like:
/path/to/APP configs/config.xml -v APP_id=12345 APP_port=2345 APP_priority=7
The exit status of this command is used to determine if the remote service is running or was successfully started or killed.
The problem I'm having is that when testing on my local machine, ssh connects to the local machine to make things easier, but pgrep called this way will also identify the ssh command that the server is running to do the check.
For example, pgrep may return:
26308 ./APP configs/config.xml APP_id=128bb8da-9a0b-474b-a0de-528c9edfc0a5 APP_nodeType=all APP_exportPort=6500 APP_clientPriority=11
27915 ssh -p 22 user#localhost pgrep -fl APP.*APP_id=128bb8da-9a0b-474b-a0de-528c9edfc0a5
So the logical next step was to change the pgrep pattern to exclude 'ssh', but this seems impossible because pgrep does not seem to be compiled with a PCRE version that allows lookaheads, for example:
bash -c -'ssh -p 22 user#localhost preg -fl "\(?!ssh\).*APP.*APP_id=12345"
This will throw a regex error, so as a workaround I was using grep:
bash -c 'ssh -p 22 user#host.domain.com pgrep -fl "APP.*APP_id=12345" \\| grep -v ssh'
This works well for querying with pgrep even though it's a workaround. However, the next step using pkill doesn't work because there's no opportunity for grep to be effective:
bash -c 'ssh -p 22 user#host.domain.com pkill -f "APP.*APP_id=12345"'
Doesn't work well because pkill also kills the ssh connection which causes the exit status to be bad. So, I'm back to modifying my pgrep/pkill pattern and not having much luck.
This environment can be simulated with something simple on a local machine that can ssh to itself without a password (in this case, APP would be 'watch'):
watch echo APP_id=12345
Here is the question simply put: How do I match 'APP' but not 'ssh user#host APP' in pgrep?
It's kind of a workaround, but does the job:
bash -c 'ssh -p 22 user#host.domain.com pgrep -fl "^[^\s]*APP.*APP_id=12345"'
...which only matches commands that have no space before the application name. This isn't entirely complete, because it's possible that the path to the executable may contain a directory with spaces, but without lookaround syntax I haven't thought of another way to make this work.
really old q but!
export VAR="agent.py"; pkill -f .*my$VAR;
I am writing a c++ code in my project that should tell whether my websphere mq server is running or not. In order to extract that we need to run "/opt/mqm/bin/amq status" to show whether it is running or not.Tricky thing is MQHOME=/opt/mqm is not constant across unix platforms.So,We agreed to a design to extract the MQHOME path from the absolute path of the process "amqzlaar0" which is an mq server process.So, we need to issue the below command that shows the process "amqzlaar0" along with its fullpath.Then,we will store the string in an array to extract MQHOME.
"ps -ef | grep amqzlaar0 | awk '{print $(NF-1)}' "
system() function is failing with exit code -1 when i use pipe symbol "|". But, if I issue just system("ps -ef"),it works.
Please help me on how to execute a pipe seperated command using system.
Your help is much appreciated.
Regards,
Sriram
I believe you should not run a command to check that amqzlaar0 is running, but query the proc(5) filesystem (on Linux).
Notice that /proc/ is not portable (e.g. not standardized in Posix). Some Unixes don't have it, and Solaris and Linux have very different /proc/ file systems.
If really want to run a command, use e.g. snprintf(3) to build the command (or std::string or std::ostringstream) then use popen(3) (and pclose) to run the command
Read Advanced Linux Programming to get a better view of Linux Programming. See also syscalls(2)
BTW, some people might have aliased e.g. grep (perhaps in their .bashrc), so you probably should put full paths in your command (so /bin/grep not grep etc...).
Just run ps -Ef. You're a C++ programmer. The equivalent of grep and awk is not hard in C++, and it's faster in C++ (doesn't require two additional processes)
I have a extremely complicated shell script, within which it calls a C++ program I want to debug via GDB. It is extremely hard to separate this c++ program from the shell since it has a lot of branches and a lot of environmental variables setting.
Is there a way to invoke GDB on this shell script? Looks like gdb requires me to call on a C++ program directly.
In addition to options mentioned by #diverscuba23, you could do the following:
gdb --args bash <script>
(assuming it's a bash script. Else adapt accordingly)
There are two options that you can do:
Invoke GDB directly within the shell script. This would imply that you don't have standard in and standard out redirected.
Run the shell script and then attach the debugger to the already running C++ process like so: gdb progname 1234 where 1234 is the process ID of the running C++ process.
If you need to do things before the program starts running then option 1 would be the better choice, otherwise option 2 is the cleaner way.
Modify the c++ application to print its pid and sleep 30 seconds (perhaps based on environment or an argument). Attach to the running instance with gdb.
I would probably modify the script to always call gdb (and revert this later) or add an option to call gdb. This will almost always be the easiest solution.
The next easiest would be to temporarily move your executable and replace it with a shell script that runs gdb on the moved program. For example, in the directory containing your program:
$ mv program _program
$ (echo "#!/bin/sh"; echo "exec gdb $PWD/_program") > program
$ chmod +x program
Could you just temporarily add gdb to your script?
Although the answers given are valid, sometimes you don't have permissions to change the script to execute gdb or to modify the program to add additional output to attach through pid.
Luckily, there is yet another way through the power of bash
Use ps, grep and awk to pick-out the pid for you after its been executed. You can do this by either wrapping the other script with your own or by just executing a command yourself.
That command might look something like this:
process.sh
#!/usr/bin/env bash
#setup for this example
#this will execute vim (with cmdline options) as a child to bash
#we will attempt to attach to this process
vim ~/.vimrc
To get gdb to attach, we'd just need to execute the following:
gdb --pid $(ps -ef | grep -ve grep | grep vim | awk '{print $2}')
I use ps -ef here to list the processes and their arguments. Sometimes, you'll have multiple instances of a program running and need to further grep down to the one you want
the grep -ve grep is there because the f option to ps will include the next grep in its list. If you don't need the command arguments for additional filtering, don't include the -f option for ps and ignore this piece
grep vim is where we're finding our desired process. If you needed more filtering, you could just do something like grep -E "vim.*vimrc" and filter down to exactly the process that you're trying to attach to
awk '{print $2}' simply outputs just the process' pid to stdout. Use $1 if you're using ps -e instead of ps -ef
My normal setup is to run such script that starts my process in 1 tmux pane and having typed something similar to the above in a bottom pane. That way if I need to adjust the filtering (for whatever reason), I can do it pretty quickly.
Usually though, it will be the same for a specific instance and I want to just attach automatically after its been started. I'll do the following instead:
runGdb.py
#!/usr/bin/env bash
./process.sh &
PID=$(ps -ef | grep -ve grep | grep -E "vim.*vimrc" | awk '{print $2}')
#or
#PID=$(ps -e | grep vim | awk '{print $1}')
gdb --pid $PID
This assumes that the original process can be safely run in the background.