Java programs run in the background for Linux

Source: Internet
Author: User
Tags shebang

1. Run the script

The script is as follows, this script has a little problem, log4j a little bit of a problem, but no impact on the operation and logging, the log is by all the console data written in the form of a file.

#!/bin/sh#author: Wangchengwei#date: 2015-7-7#desc: Run java application#Java的安装目录java_home=/usr/lib/java-1.7.0#运行程序所使用的用户Owner=root#Java程序的目录App_home=/software/taxidata/socketdxptaxi#Main方法的类App_mainclass=com.tiamaes.gjds.socket.server.minaserver#日志文件log_file=$APP _home/logs/socket.log#设置CLASSPATHClasspath=$CLASSPATH:$APP _home/socketdxptaxi.jar#循环将lib文件夹下所有的jar添加到CLASSPATH forIinch "$APP _home"/lib/*.jar; DoClasspath="$CLASSPATH":"$i"   Done#设置运行参数java_opts="-xms512m-xmx512m-xmn256m-djava.awt.headless=true-xx:maxpermsize=128m"#echo $CLASSPATH;Psid=0#检查Java程序是否运行Checkpid() {javaps= '$JAVA _home/bin/jps- L| Grep$APP _mainclass`if[-N"$javaps"]; ThenPsid= 'Echo $javaps| Awk' {print '} '`ElsePsid=0    fi}#运行程序Start() {Checkpidif[$psid -ne 0]; Then        Echo "WARN:$APP _mainclass already started! (pid=$psid) "    Else        Echo "Starting $APP _mainclass..."Java_cmd="Nohup $JAVA _home/bin/java $JAVA _opts -classpath $CLASSPATH $APP _ MAINCLASS >> $LOG _file 2>&1 & "Su-$OWNER-C"$JAVA _cmd"Checkpidif[$psid -ne 0]; Then            Echo "Started $APP _mainclass (pid=$psid) [OK]"        Else            Echo "Started $APP _mainclass [FAILED]"        fi    fi}#停止程序Stop() {Checkpidif[$psid -ne 0]; Then        Echo "stoping $APP _mainclass... (pid=$psid) "Su-$OWNER-C"Kill $psid"Checkpidif[$psid -ne 0]; Then            Echo "stoping use kill-9"Su-$OWNER-C"kill-9 $psid"        fiCheckpidif[$psid -eq 0]; Then            Echo "stoped $APP _mainclass [OK]"        Else            Echo "stoped $APP _mainclass [Failed]"Stopfi    Else        Echo "WARN:$APP _mainclass is not runing"    fi}#查看状态Status() {Checkpidif[$psid -ne 0]; Then        Echo "$APP _mainclass is runing (pid=$psid)"    Else        Echo "$APP _mainclass is not runing"    fi}#帮助信息Info() {Echo "System Information:"    Echo "****************************"    Echo' Head-n1/etc/issue 'Echo' Uname -A`Echo    Echo "Java_home=$JAVA _home"    Echo`$JAVA _home/bin/java-version 'Echo    Echo "App_home=$APP _home"    Echo "app_mainclass=$APP _mainclass"    Echo "****************************"}#$1 indicates that the first parameter, such as./run.sh start, is received. Then $ $ is start Case "$" inch    ' Start ') start;;' Stop ') stop;;' Restart ') stop start;;' Info ') info;;' status ') status;; *)Echo "Usage:  $ {start|stop|restart|status|info}"    Exit 1EsacExit 0;
2. Analysis of Knowledge points

Shell's basic knowledge is not to repeat, their own Baidu study. Focus on the next few points.

2.1. Running the jar
JAVA_OPTS="-Xms512m -Xmx512m -Xmn256m -Djava.awt.headless=true -XX:MaxPermSize=128m"$J$C$APP_MAINCLASS

Java running the jar is the option to set Java operating parameters, Classpath, and so on.

Java run parameters are primarily memory settings
-XMS: Initial heap size, minimum memory used, higher CPU performance This value should be set to a larger
-xmx:java heap maximum, maximum memory used
-xx:permsize: Setting a permanent storage area for memory
-xx:maxpermsize: Set a permanent storage area for maximum memory
The heap size of the-xmn:young generation, typically set to one of the 3, 4 points of Xmx

The classpath is used to set the jar to run as a dependent jar

2.2. JPS commands in Java

The JPS (Java Virtual machine process Status Tool) is a command that JDK 1.5 provides to show all current Java process PID, and is simple and practical, ideal for linux/ Simple view of the current Java process on the UNIX platform.
Compare Common parameters:
-Q displays only the PID, does not display the class name, the jar file name, and the arguments passed to the main method
-m output parameters passed to the main method, which may be null on the embedded JVM
-m output parameters passed to the main method, which may be null on the embedded JVM
-L OUTPUT The full package name of the main class of the application or the full path name of the application's jar file
-V Output parameters passed to the JVM
In this example we are using Jps-l, using the Jps-l | grep $APP _mainclass can see if there is a program in the process based on the class name where the main method resides. The PID of the process is then obtained through awk.

2.3. Use of the SU command
$OWNER"$JAVA_CMD"

The above command indicates that the command is executed using the $OWNER user, followed by the-C command. The advantage of doing this is that the user's environment variable is executed, and that our app runs under the user we specify.

2.4, Nohup

Purpose: Do not hang up to run the command, said the simple point is to let the program can run in the background.
Syntax: Nohup Command [Arg ...] [&]

Description: The nohup command runs commands specified by the command parameter and any related ARG parameters, ignoring all hang-up (SIGHUP) signals. Use the Nohup command to run a program in the background after logging off. To run the Nohup command in the background, add & (the symbol representing "and") to the end of the command.

The output is appended to the Nohup.out file in the current directory, regardless of whether the output of the Nohup command is redirected to the terminal. If the nohup.out file for the current directory is not writable, the output is redirected to the $HOME/nohup.out file. If no file can be created or opened for appending, then the command specified by the commands parameter is not callable. If the standard error is a terminal, redirect all output of the specified command to the standard error as standard output to the same file descriptor

This means that our Java program runs in the background, and the log recorded by the program to $log_file,> means write (clear the content before writing the content),>> means append

The meaning of 2>&1

For & 1 More accurate should be the file descriptor 1, and 1 is generally representative of Stdout_fileno, in fact, this operation is a dup2 (2) call. He standard output to All_result, and then copy the standard output to the file descriptor 2 (stderr_ Fileno), the consequence is that file descriptors 1 and 2 point to the same file table entry, or the wrong output is merged. where 0 means keyboard input 1 means that the screen output 2 indicates an error output. REDIRECT standard error to standard output, and then throw it under/dev/null. In layman's words, all standard output and standard errors are thrown into the trash.

2>&1 is redirecting standard error to standard output, where the standard output has been redirected to the $log_file file, and the standard error is output to the $log_file file.

For more information, you can view this post: http://blog.csdn.net/annicybc/article/details/4814872

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java programs run in the background for Linux

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.