将 Java 程序作为 Linux 的 Daemon 进程以及防止程序多次运行的方法

(一)使 Java 程序成为 Linux 的 Daemon 进程

    Java 程序是编译后通过 Java 虚拟机(JVM)解释执行的,从执行“java SomeProgram”开始直到程序结束才会把命令行交还给用户,中途用户若退出登录或关闭 SHELL 则会中断程序的执行。但现实中有需要做某些不需要和用户交互的服务性程序,需要长驻内存执行又不影响用户其他工作,如 Linux 的众多 Daemon 进程一样。用下面介绍的方法可以使 Java 程序也做到:

> nohup java SomeProgram &

    nohup 是 Linux 的一个命令,可以使其后执行的进程成为 init 的子进程,不受到其他 hangup signals 的影响,
只有用 kill 命令或重启机器才会消失。而命令行最后的“&”,表示将命令行交还给用户。


(二)使 Java 程序只允许运行一次,即只允许一个实例保留在内存中

    有时希望程序只运行一次,再执行的时候提醒本程序已在运行中。但由于 Java 程序由 JVM 执行,除非通过 JNI 技术或特殊的类库,否则无法读取操作系统的进程,也无法与其他在运行的 JVM 通讯。Java 1.4 新增了 nio 类库,其中的 FileLock类可以对操作文件加锁,就可以实现以上目的了。下面是实现方法:

import java.io.*;
import java.nio.channels.*;
public final class OneInstance {
    public static void main(String[] args) {
        System.out.println("Program Start...");
        String filename = new String("/tmp/test.txt"); // Here you can change filename to Windows format
        File testFile = new File(filename);
        RandomAccessFile raf; // Here you can use either FileInputStream or FileOutputStream
        FileChannel fc;
        FileLock fl;
        try {
            testFile.createNewFile();
            if (testFile.canWrite() == true) {
                raf = new RandomAccessFile(testFile, "rw");
                fc = raf.getChannel();
                fl = fc.tryLock();
                if (fl == null || fl.isValid() == false) {
                    System.out.println("The File is using by another program!");
                } else {
                    System.out.println("The File is locking by me! My Name is: " + args[0]);
                    raf.writeChars("I am running... My name is: " + args[0]);
                    Thread.sleep(1000 * 30); // You can try to run other program between this while
                    fl.release();
                }
                raf.close();
            }
        } catch (FileNotFoundException fnfe) {
            System.out.println(fnfe);
        } catch (SecurityException se) {
            System.out.println(se);
        } catch (ClosedChannelException cce) {
            System.out.println(cce);
        } catch (OverlappingFileLockException ofle) {
            System.out.println(ofle);
        } catch (IOException ioe) {
            System.out.println(ioe);
        } catch (Exception ex) {
            System.out.println(ex);
        }
        System.out.println("Program End!");
    }
}
> javac OneInstance.java
> java OneInstance abc
Program Start...
The File is locking by me! My Name is: abc
(在30秒内开另一个SHELL)
> java OneInstance def
Program Start...
The File is using by another program!
Program End!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值