linux服务器open office 进程总退出问题解决方法
在项目中使用open office做有生成证书(pdf)功能,但open office服务进程总是莫名其妙退出,解决方案如下。
方法一:程序捕获异常
open office进程挂掉会出现连接异常,则可以在代码中增加对OpenOffice的ConnectException异常检测,如果捕获该异常,系统就连接open office服务器并执行restart脚本重启open office服务。代码如下:
try {
// ......
connection.connect();
// ......
} catch (ConnectException e) {
logger.info("连接异常openoffic服务器......,ip={}", ip);
Connection sshConn = new Connection(ip, 22);
Session session = null;
try {
sshConn.connect();
boolean isAuthenticated = sshConn.authenticateWithPassword("root", "123456");
if (isAuthenticated) {
session = sshConn.openSession();
logger.info("重启open office服务......");
session.execCommand("sh /root/restart.sh", "UTF-8");
InputStream sessionIn = new StreamGobbler(session.getStdout());
BufferedReader brs = new BufferedReader(new InputStreamReader(sessionIn));
String line = brs.readLine();
logger.info("重启open office服务,启动结果输出,{}", line);
} else {
logger.error("连接ssh失败,用户名或密码错误");
}
} catch (Exception se) {
logger.error("连接ssh失败,ip=" + ip, se);
} finally {
if (session != null) {
session.close();
}
sshConn.close();
}
// 抛出异常,让当前的任务记录错误信息,下一个任务会正常进行
throw e;
}
方法二:使用linux定时任务
使用linux的cron定时任务管理,每分钟都执行一下脚本检测open office进程是否存在,不存在则重启服务,脚本如下
#!/bin/sh
OPENOFFICEPID=`ps -ef|grep "/opt/openoffice4/program/soffice"|grep -v grep|grep -v grep|awk '{print $2}'`
if [ ! -n "$OPENOFFICEPID" ]; then
echo "OPENOFFICEPID is empty, start openoffice"
nohup soffice -headless -accept="socket,host=192.168.1.1,port=8100;urp;" -nofirststartwizard &
else
# kill all openoffice process
# ps -ef|grep "/opt/openoffice4/program/soffice"|grep -v grep|grep -v grep|awk '{print $2}' | xargs kill
echo "OPENOFFICEPID is $OPENOFFICEPID is started!"
fi
备注:定时任务添加步骤如下:
crontab -e
# 进入vim编辑,添加一行定时任务并保存
# 格式: 分 时 日 月 周 命令 参数
*/1 * * * * /bin/sh /root/restart.sh
# 查看任务列表
crontab -l