Java语言以其跨平台性和简易性而著称,在Java里面的lang包里(java.lang.Runtime)提供了一个允许Java程序与该程序所运行的环境交互的接口,这就是Runtime类,在Runtime类里提供了获取当前运行环境的接口。 其中的exec函数返回一个执行shell命令的子进程。exec函数的具体实现形式有以下几种:
public Process exec(String command) throws IOException
public Process exec(String command,String[] envp) throws IOException
public Process exec(String command,String[] envp,File dir) throws IOException
public Process exec(String[] cmdarray) throws IOException
public Process exec(String[] cmdarray, String[] envp) throws IOException
public Process exec(String[] cmdarray, String[] envp,File dir) throws IOException
代码如下:
try
{
String commands = "ls -l";
Process process = Runtime.getRuntime().exec (commands);
InputStreamReader ir=new InputStreamReader(process.getInputStream());
BufferedReader input = new BufferedReader (ir);
String line;
while ((line = input.readLine ()) != null){
System.out.println(line);
}
}//end try
catch (java.io.IOException e){
System.err.println ("IOException " + e.getMessage());
}
上面的代码首先是声明了一个代表命令的字符串commands,它代表了ls -l 这个命令。之后我们用Runtime.getRuntime().exec(commands)来生成一个子进程来执行这个命令,如果这句话运行成功,则 命令 ls -l 运行成功(由于没有让它显示,不会显示ls -l 的结果)。后面的流操作则是获取进程的流信息,并把它们一行行输出到屏幕。
2)执行带有参数的命令(尤其是参数需要用引号的)时则需要用String的数组来表示整个命令,而且要用转义符把引号的特殊含义去除,例如我们要执行 find / -name "*mysql*" -print 时,用如下代码
try
{
String[] commands = new String[]{"find",".","-name","*mysql*","-print"};
Process process = Runtime.getRuntime().exec (commands);
InputStreamReader ir=new InputStreamReader(process.getInputStream());
BufferedReader input = new BufferedReader (ir);
String line;
while ((line = input.readLine ()) != null){
System.out.println(line);
}
}//end try
catch (java.io.IOException e){
System.err.println ("IOException " + e.getMessage());
try
{
String commands = "/root/test/checkfile.sh";
Process process = Runtime.getRuntime().exec (commands);
InputStreamReader ir=new InputStreamReader(process.getInputStream());
BufferedReader input = new BufferedReader (ir);
String line;
while ((line = input.readLine ()) != null){
System.out.println(line);
}
}//end try
catch (java.io.IOException e){
System.err.println ("IOException " + e.getMessage());
1)system(shell命令或shell脚本路径);
system()会调用fork()产生子进程,由子进程来调用/bin/sh-c string来执行参数string字符串所代表的命令,此命令执行完后随即返回原调用的进程。在调用system()期间SIGCHLD 信号会被暂时搁置,SIGINT和SIGQUIT 信号则会被忽略。
返回值:如果system()在调用/bin/sh时失败则返回127,其他失败原因返回-1。若参数string为空指针(NULL),则返回非零值。如果 system()调用成功则最后会返回执行shell命令后的返回值,但是此返回值也有可能为system()调用/bin/sh失败所返回的127,因此最好能再检查errno 来确认执行成功。
例:在~/test/目录下有shell脚本test.sh,内容为
#test.sh
echo hello
{
system("~/test/test.sh");
}
[root@localhost test]$./system_test
hello
[root@localhost test]$
2)popen(char *command,char *type)
main
{
FILE * fp;
charbuffer[80];
fp=popen(“~/myprogram/test.sh”,”r”);
fgets(buffer,sizeof(buffer),fp);
printf(“%s”,buffer);
pclose(fp);
}
[root@localhost test]$ gcc popentest.c -o popentest
[root@localhost test]$ ./popentest
/root/test
[root@localhost test]$