I have inherited an extract job program which is a Java program that connects to a database and produces a file from a Unix shell script. At times, I can see the Java program is terminated abnormally and starts executing the remainder of the Unix script by zipping the extract. This is causing a lot of reconciliation issues.
The code is structured as follows:
INSTANCE_NAME=1
PROCESS_NAME=benefitpayment
cd utils
FAIL=0
sh benefitpaymentprocesswithdates.sh $PROCESS_NAME $INSTANCE_NUMBER $1 $2
for job in $dPidLst
do
wait $job || let "FAIL+=1"
done
echo $FAIL
if [ "$FAIL" == "0" ];
then
echo "About to secure file..."
zip -P <password> export.txt secure.zip
...
...
else
echo "FAIL! ($FAIL)"
fi
The $dPidLst is set in the inner Unix script(benefitpaymentprocesswithdates.sh) to call a Java wrapper and is set as:
java program called to generate a file
dPidLst=`jobs -p`
In either of the successful or failure cases, this "dPidLst" is always NULL.
The dPidLst is not exported in the inner script. The script was designed in that manner.
Should dPidLst be exported back to this main program? How do I make this script fool proof in the sense, if the Java program terminates abnormally, it should not execute the remainder of the Shell script? of zipping the file.
The value of dPidLst that you set in benefitpaymentprocesswithdates.sh will not be visible in your calling script.
When you run the benefitpaymentprocesswithdates script, it runs in its own process, and that process gets its own variables.
To pass the process id list back to your script, you need to use a mechanism other than shell variables or environment variables
e.g. at the end of benefitpaymentprocesswithdates.sh, do
echo $dPidList
And when you call it instead of
sh benefitpaymentprocesswithdates.sh
do
dPidList=$(sh benefitpaymentprocesswithdates.sh)
If all it is doing is calling jobs -p, there's no reason to have it in a separate script, of course.
Related
Is this a simple and good way to execute a Shell command via Java?
Runtime.getRuntime().exec( some command );
Or is this bad practice?
It depends.
The original purpose and basic functionality of a Unix shell is to let you run programs, optionally passing them arguments. For example the command ls runs the ls program, and the command grep foo bar runs the grep program with the arguments foo and bar. If your command only runs a (fixed) program with fixed if any arguments, Runtime.exec can do it. There are two subcases:
the overloads taking a String parse the line into 'words' (program name and arguments) using any whitespace; this is essentially the same as the default parsing (with no quoting) done by standard shells.
if you need any different parsing, for example if your command would use any quoting in shell, you must do that parsing yourself and pass the results to one of the overloads taking a String[].
But note that when you run a program from an interactive shell -- one using a terminal or equivalent (sometimes called a console) for input and output -- the program's input and output default to that terminal. The I/O for a program run by Runtime.exec is always pipes from and to the Java process, and some programs behave differently when their input and/or output is/are pipe(s) -- or file(s) -- instead of a terminal. Plus you must write code to send (write) any desired input and receive (read) any output. Of course, shells can be and sometimes are run without a terminal too.
However, shells can be and routinely are used to do much much more than the basics:
shell can execute commands with contents different from the input by variable (formally parameter) substitution (possibly with modification/editing), command substitution, process substitution, special notations like squiggle and bang, and filename expansion aka 'globbing' (so called because in the early versions of Unix it was done by a separate program named glob). Runtime.exec doesn't do these, although you can write Java code to produce the same resulting command execution by very different means.
shell executes some commands directly in the shell rather than by running a program, because these commands affect the shell process itself,
like cd umask ulimit exec source/. eval exit alias/unalias, or variables in the shell like set shift unset export local readonly declare typeset let read readarray/mapfile,
or child process like jobs fg bg, or special parsing like [[ ]] and (( )) (in some shells). These are called 'builtin' and Runtime.exec can't do them,
with two partial exceptions: it can run a program with a different working directory and/or env var settings, equivalent to having previously executed cd or export or equivalent.
Shell also often has builtins that duplicate, or modify, a 'normal' program; these commonly include test/[ echo printf kill time. Runtime.exec can only do the program version, not the builtin version.
shell has control structures (compound commands) like if/then/else/elif/fi and while/for/do/done and trap && || ( ) { }. Runtime.exec can't do these, although in some cases you could use Java logic to produce the same results.
shell can also have user-defined functions and aliases that can be used as commands; Runtime.exec does not.
shell can redirect the I/O of programs it runs, including forming pipes. Runtime.exec can't do these, but see below.
Since 1.5, Java also has ProcessBuilder, which provides the same functionality and more, in a more flexible and arguably clearer API, and thus is generally recommended instead. ProcessBuilder does support redirecting I/O for the program it runs, including using the terminal/console if the JVM was run on/from one (which is not always the case), and since 9 it can build a pipeline. It does not have the word-splitting functionality of Runtime.exec(String) but you can easily get the same result with string.split("[ \t]+") or in most cases just " +".
Note shell is itself a program, so you can use either Runtime.exec or ProcessBuilder to run a shell and pass it a command, either as an argument using option -c (on standard shells at least) or as input, and unsurprisingly this shell command can do anything a shell command can do.
But this can be a portability issue because different systems may have different shells, although any system claiming Unix certification or POSIX conformance must have a shell named sh that meets certain minimum requirements.
The actual shell used on different systems might be any of bash dash ksh ash or even more. OTOH this is true for other programs as well; some programs that typically differ significantly on different systems are awk sed grep and anything to do with administration like netstat.
A few of the existing Qs that show shell commands that don't work in Runtime.exec at least as-is:
a command for sherlock.py is interpreted differently from linux command line and java process api
Execute shell script multiple commands in one line using Process Builder in Java (Unix)
Check in Java if a certain application is in focus
Problem in executing command on AIX through Java
ProcessBuilder doesn't recognise embedded command
File not Found when executing a python scipt from java
Java system command to load sqlite3 db from file fails
Curl To Download Image In JAVA
Keytool command does not work when invoked with Java
use javap from within a java program on all the files
Using SSMTP and ProcessBuilder
Process Builder Arguments
Whitespace in bash path with java
java.lang.Runtime exception "Cannot run program"
Why does Runtime.exec(String) work for some but not all commands?
How to save Top command output in a text or csv file in java?
Execute bash-command in Java won't give a return
Using Java's Runtime.getRuntime().exec I get error with some commands, success with others -- how can this be determined?
Java and exec command - pipe multiple commands
Java exec() does not return expected result of pipes' connected commands
How to make pipes work with Runtime.exec()?
How to use Pipe Symbol through exec in Java
In Runtime.getRuntime().exec() getting error: /bin/bash: No such file or directory
Java exec linux command
How to use pipes in a java Runtime.exec
Java Runtime.getRuntime().exec and the vertical bar
Whenever I execute terminal command from code it gives "cannot run program" error=2 No such file or directory
Command line proccess read linux in java
Java Command line system call does not work properly
So I'm using the coproc command in a script to run a java program and to feed input to it, as follows:
#!/bin/bash
echo Script started.
coproc java -jar MultiThreadedFileProcessor.jar
echo start >&${COPROC[1]}
echo Script terminated.
I'd like to be able to write another script which can pass more input to this program (e.g. a command which will tell the program to run termination routines).
Is there any way that I can access the stdin of the coprocess from another script? My current attempt at a termination script is as follows:
#!/bin/bash
echo Script started.
echo terminate >&${COPROC[1]}
echo close >&${COPROC[1]}
echo Script terminated.
This gives me an ambiguous redirect error however, I'm guessing because COPROC[1] is only defined in the script that creates the coproc.
How else, if at all, can I write a script that will accomplish my goal of passing a line to the java program?
COPROC is an array local to the first script - you will never be able to access that from another script.
On Linux, you could access /proc/$pid/fd/$n with $pid being the pid of the first script and $n being the fd stored in ${COPROC[1]}. Both have to be communicated somewhere (a pid file and likewise an "fd file"), but in that case you might better be off creating a named pipe (mkfifo) and use that instead of creating a coproc in the first place. Something like this (not tested) codes:
Script 1:
mkfifo fifoname
exec 5>fifoname
java <fifoname &
echo close >&5
Script 2:
exec 5>fifoname
echo terminate >&5
echo close >&5
What is the close command supposed to do? The java program will see
close
terminate
close
Does that make sense to the java program?
I am starting a Java code from Bash script called start.sh. The Bash script fires up the Java code and then the Java code runs. At the end of the Java program, I want to send a signal back to the Bash script to terminate. Keep in mind that the Bash script runs with PID = 1. And I have to kill the PID 1 process.
I have the bash script set up such that it runs in an infinite loop and waits for a termination signal:
#!/bin/bash
# Run the java code here..
# Listen for an exit command.
trap 'exit 0' SIGTERM
while true; do :; done
I am using Docker instances and the signal is sigterm. I am following this tutorial: https://www.ctl.io/developers/blog/post/gracefully-stopping-docker-containers/ which explains how to send a sigterm from command line. I want to automate this process and close/kill the docker instance from inside as soon as the Java program ends.
How do I send the signal back to the bash script that started the Java code in the first place?
Should I follow
this method to send a signal as arguments to the bash script? Or will it start another bash script with a different PID (not 1).
Help needed!
Write 'set -e' in second line in bash script.
Dont use trap and while. Replace it by
'exec your_java_code_run'.
By this way docker get SIGTERM after java code run end.
Exemple:
#!/usr/bin/env bash
set -e
someOtherCodeIfNeed
exec your_java_code_run
I'm trying to restart process when OOME happens. Java binary is launched using two shell scripts, one of them imports other. I don't have any control of the first one but can modify the second one as I want.
This is a prototype what I'm trying to do:
First shell script test.sh:
#!/bin/sh
JAVA_OPTS="$JAVA_OPTS -Xmx10m"
. test1.sh
echo $JAVA_OPTS
java $JAVA_OPTS $es_params TestMemory
Second shell script test1.sh:
#!/bin/sh
pidfile="test.pid"
touch $pidfile
params="$parms -Dpidfile=$pidfile"
kill_command="kill -9 \$(cat $pidfile)"
dir=$( cd $(dirname $0) ; pwd -P )
path="$dir/$(basename $0)"
start_command="$path $#"
restart_command="$kill_command;sleep 2;$start_command"
JAVA_OPTS="$JAVA_OPTS -XX:OnOutOfMemoryError=\"$restart_command\""
Generally what it does is JAVA_OPTS is constructed inside test1.sh and then used to run Java binary, which just writes PID in pidfile and then creates OOME.
Problem happens during execution, java can't understand what is a parameter and what is a class to run. I think it might be a problem of quoting, I tried different ways to escape JAVA_OPTS, but without any result. I'm either getting:
Unrecognized option: -9
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
Or
Error: Could not find or load main class "-XX:OnOutOfMemoryError=kill
If I just take a value of JAVA_OPTS and put it manually in test.sh it runs perfectly.
Any ideas how can I change test1.sh to make it work? I think I tried almost every possible way of putting double and single quotes, but without any success. Also if I put restart_command in restart.sh file and use it instead of the variable, it works fine.
After running set -x I saw that shell modifies every single space character to ' ' - adds ' on both sides. Escaping doesn't gives any result. Any idea how to avoid this? So final commend is:
+ java -Xmx10m '"-XX:OnOutOfMemoryError=kill' '$(cat' 'test.pid);sleep' '2;/Users/davidt/test/TestMemory/bin/test.sh' '")' -Des.pidfile=test.pid TestMemory
Update
I can run simplified command successfully
java "-XX:OnOutOfMemoryError=echo 'Ups'" $es_params TestMemory
But it seems a general problem, shell just hates spaces into variables I guess:
JAVA_OPTS="\"-XX:OnOutOfMemoryError=echo 'Ups'\""
set -x
java $JAVA_OPTS TestMemory
This script fails and the last line is interpreted as:
java '"-XX:OnOutOfMemoryError=echo' ''\''Ups'\''"' TestMemory
I tried different options to escape
This is a shell problem. Based on the evidence, I'd say that one of the ; characters ... and possibly some why space ... is being interpretted by the shell when you don't want / need this to happen.
If you run set -x in the shell before running the command that is trying to start the JVM, you will see the actual command that is being used.
It seems shell translates every single space to ' ',
Not exactly. The single quotes are inserted by the shell into the output you are getting from set -x. They simply indicating where the argument boundaries are. They are not really there ... and they are certainly NOT being passed to the java command.
Any idea how to [a]void it?
What you need to do is start from the (final) command that you are trying execute ...
java -Xmx10m -XX:OnOutOfMemoryError="kill NNNN;sleep 2;/Users/davidt/test/TestMemory/bin/test.sh" -Des.pidfile=test.pid TestMemory
... and work backwards, so that the shell variables, expansions and escaping give you what you need.
The other thing to note is that this:
java -Xmx10m -XX:OnOutOfMemoryError="kill $(cat test.pid); ..."
probably won't work. The kill $(cat test.pid) command is using shell syntax and requires shell functionality to interpolate the contents of the PID file. I doubt that the JVM is going to know what to do with that. (Or more accurately. It will do what you have literally told it to do, but that will not be what you want ...)
If you really need to interpolate the pid file content when the restart command is run as you appear to be trying to do, then suggest that turn the restart command into a free-standing shell script, and set the file mode so that it is executable. It will be simpler and a lot easier to get working.
As a general piece of advice, is is a bad idea to be too clever with shell scripts. The exact semantics of variable expansion and command parsing are rather tricky, and it is easy to get yourself really confused ... if you are trying to do this at multiple levels.
I ended up put the script I wanted to execute in a separate file and gave it as a parameter to JVM to execute when OOME happens.
echo "echo 'UPS'" >> oome_happened.sh
JAVA_OPTS="\"-XX:OnOutOfMemoryError='oome_happened.sh'\""
set -x
java $JAVA_OPTS TestMemory
Like #DaTval said, you should put the command in a script. The script should be someting like.
#!/bin/bash
kill -9 $PPID
Kill the caller of scripts.
I require a method to easily restart/replace bash scripts without manually stopping/starting the process over again.
Here's how my current script works:
#!/bin/sh
while true
do
echo "1"
java -server -Xms2G -jar game.jar nogui
done
Basically, if the game stops, it will automatically restart however, the script is already loaded into memory so if I was to modify it, I would have to manually kill the script and start it up again in order for the changes to take effect. I'm running at least 200 instances of the game server itself so, it would not be intelligent to do this manually and kill, then start each script manually again.
When the game server stops, I wish for it to update the script, here is an example of what I may want to do:
#!/bin/sh
while true
do
echo "1"
echo "2"
java -server -Xms2G -jar game.jar nogui
done
However, I'd need to physically stop the script and start it again myself in order for it to add the new 'echo "2"', I need an easier way to replace the running script.
The script itself will download the updated script when the game stops (so it will automatically start again.
How can I make the script unload itself from memory, and use the new script?
If I cannot do this, is there any alternative method you can suggest?
The alternative method is to use a process supervision tool such as runit, daemontools, upstart, supervisord, systemd, etc.
For any of these, you would write only the following script:
#!/bin/sh
exec java -server -Xms2G -jar game.jar nogui
...and the supervision tool would be responsible for restarting the server on exit, rereading the script (and thus responding to updates) each time it needs to be run.
These tools give you far more features than just reliable restarts -- they typically also manage logging, staged shutdown (ie. TERM + timeout + KILL), custom cleanup commands, signal hooks, etc.
See also the ProcessManagement page on the freenode #bash wiki.
If you can't use a process management system (and you really, really should!), you can have the script exec itself. That is to say:
#!/bin/sh
# ...do stuff here...
exec "$0" "$#" # and restart
Note that this is unreliable for various reasons related to BashFAQ #28.
Call the following file myscript.sh. It reloads itself into memory every time that the game stops:
#!/bin/sh
java -server -Xms2G -jar game.jar nogui
exec /path/to/myscript.sh