Command & four elements of the command line to compile and run Java programs in Java & fork child process

Command line history and genre:

  • UNIX family
    • POSIX standard
    • macOS
    • Linux
    • Windows Subsystem for Linux
  • Windows

First, the four elements of command

Composed of four elements indispensable command, the following four elements can be completely identical to "revive" ⼀ command, a variety of strange problems you encounter, the reason given is ⼀ ⼀ of four elements.

  • Executable (Executable)
  • parameter
  • Environment variables (Environment variable)
  • Working directory (Working directory)

1. Working Directory

Start command current path of the cursor, the relative path is relative to this path. Enter the pwdcommand to view the current working directory is located.
Can be understood: command (executable) itself is present in a directory, you need to find the command you execute a command, usually according PATHto find the executable environment variable, or directly using the absolute path of the command (using the whichView ), the tool now get this, do not care where he comes from tools, pay attention to the work place in which, while working title [directory] is the tool of the current work place.

2. Environment Variables

Variable is divided into local variables and global variables of the environment, the environment and the environmental variables are strongly bound, and is arranged to transfer a wide range of an application, environment variables may be used to pass parameters to different programs and configuration, for example CLASSPATH, and GOPATH.
See all environment variables export.

Local variables

Scope of local variables defined in the shell to create them. Meaning that the child does not go to inherit. local function can be used to create local variables, but use only within the function. It may be a local variable value given by a simple name or a variable set, with built-in functions to declare set, or may be omitted.

name=yue
echo $name
Environment variables (global variables)

Environment variables, also known as global variables, to distinguish it from a local variable, generally, the environment variables should be capitalized, environment variables are already using exportvariable built-in command to export.
Temporary environment variables exportdeclared directly to the command line, the variable fail when you close the shell:

export NAME=yue
echo $NAME # yue

Permanent (permanent valid for the current user) is the need to exportcommands written in the startup configuration file ~/.bash_profile, the syntax above. After saving the file if you want to take effect in the current shell immediately executed source .bash_profile, otherwise the newly opened shell to take effect.
Whether temporary or permanent environment variable, sub-shell will inherit the current environment variable parent shell, but can not reverse pass . You can go to perform bashto create a sub-shell to be a test.

You can also quickly pass an environment variable (only this line currently executing command effective):

NAME=Tony go run main.go
#之后这个环境变量就不存在了
echo $NAME # 空空如也
System Variables

If you are a Java development environment installed on Windows, you must remember to configure the system PATH environment variable, so as to require the path when PATH mentioned this, find the corresponding executable and run it.
So as PATHenvironment variables such system level, than git bash ~/.bash_profilescope environment variable in bash terminal stage of a wider, after all, the operating system is the dad.
I want to prove it is very simple, go to set system environment variables, such as the name JUST_TEST, and then win + R to open a cmd, execute echo %JUST_TEST%, you can see just set the variable value.

Process (Process)

It is the smallest unit of a computer program running exclusively file its own memory space and resources, and each process bound to a set of environment variables. Child process is fork out by the parent process, environment variables (global variables) can be inherited by child processes, all operating systems and programming languages support environment variables.
For example, the current shell environment variable is set XXX, the node then proceeds to the execution environment in the current environment, can process.env.XXXbe inherited (As mentioned above, the local variable is not inherited by child processes) to see the environment variable.

3. executable program

What counts as an executable program

Windows, exe/bat/comthe file extension is considered to be executable by Path;
UNIX / Linux seen xprivileges ( ls -l), you can execute permissions;

Where to find ⾥ program?

In Windows Path environment variable and is the current directory;
in UNIX / Linux PATH environment variable.
Executables are looking for the path from the path, if set to an empty string, it will not be found.
If the current directory in the executable program for UNIX system can ./xxxexecute, .on behalf of the current directory.
For Windows, cmd directly enter the name of the executable program, as suffix, plus without anything, will automatically find exe/bat/comsuch a suffix.

Specifies the interpreter (shebang) in the first frame ⾏ script

Editing a xxx.shtime file, you can specify another first line of the interpreter in a shell script:

#!/usr/bin/env node
console.log(123)

It indicates the current execution context, look for the node executable program to explain the current script, then of course it will find the path from node path environment variable, which is equivalent to write in fact be executed directly from the command line node xxx.sh.

Alias ​​(alias)

~ / .bash_profile interactive, login operation mode into the bash
~ / .bashrc interactive mode into the non-login bash running
.bash_profile is read every time a user login, all commands will be executed inside bash .
When read .bashrc file to call another bash shell in the bash shell, that is, and then type the command in a shell bash will read the file when you start a new shell. This can effectively isolate the desired login and sub-shell environment.
Generally calls the script .bash_profile .bashrc configuration in order to unify the user environment.

Use a shell in aliasthe alias command set, belonging to a local variable, only the current of this layer active shell environment, written ~/.bash_profileafter each new login shell will read, but because of aliasthe configuration of the alias belong to a local variable, plus when you create a child does not read shell .bash_profile(unless written .bashrcin), and therefore would not set an alias for sub-shell:

vim ~/.bash_profile

# 写入如下内容,保存后 source 一下立即生效

export NAME=Tony
export AGE=25

echo '你好哇~'

alias ~='cd ~'
alias cdproject='cd ~/Projects'

Login whenever you open a terminal, you will see 你好哇~that this explanation after each open a terminal, the system is equivalent to a new fork terminal bash process, inherited the system environment variables, but also perform startup files, that is .bash_profile.

Linux file permissions

Linux foundation - rights management chmod command

4. Parameters

All of which are behind the executable program parameters. UNIX system convention as follows (Java does not strictly comply):
agree that one: -behind with only one character, but can be combined, ls -althequivalent to the ls -a -l -t -h
convention II: --followed by a word ls --allequivalent tols -a

If the parameter spaces, spaces will be divided into a plurality passed to the executable program;
parameters without quotation marks or " "double quotation marks, the command-line parameters will be replaced and expanded variables;
use ' 'single quotes, the command line will not do anything special processing, this parameter is used to declare a whole:

export A=123
echo wan$A.m    # wan123.m
echo "wan$A.m"  # wan123.m
echo 'wan$A.m'  # wan$A.m

If the parameter is to include a single quote ' ', then double quotes may then " "wrap or escape:

echo \'I am a boy\'   # 'I am a boy'
echo "'I am a boy'"   # 'I am a boy'

Second, use the command to compile and run Java programs

Java world where all the tools are only one thing: the command-line stitching

1. Compile and run

javac Main.java # 源文件编译成字节码
ls # 查看编译结果 Main.class Mian.java
java Main # 运行

In Java:
System.getenv()View environment variables
System.getProperty()see the system properties
delivery system properties To Dbegin with, we should pay attention to the writing position, if at Mianthe back became Mainthe parameters, that is, the first day of school was exposed to the Java mianmethod String[] argsparameters. The pass called AAA, the value 123of properties:

java -DAAA=123 Main

user.dirView the current working directory
java.versionto view the current version jdk

2. -classpath (-cp) parameters

import junit.extensions.ActiveTestSuite;
public class Main {
        public static void main(String[] args) {
                System.out.println(ActiveTestSuite.class.getName());
        }
}

Direct execution javac Main.javawill not find the error.
So for the introduction of third-party libraries, compile-time use -classpathto specify a search path jar package (assuming that this jar package in the current working directory):

javac -cp junit-3.8.2.jar Main.java

The successfully compiled, because the jar package is a normal zip file, which put a bunch in line with the class file. Fully qualified class name (FQCN of) the package name and a folder class is one to one.
This commands, javacis executable executable program, followed by all parameters -classpath(-cp)specified jar package path, Main.javait is about to be compiled file. Main.javaThere is a ActiveTestSuite, this class certainly can not fall from the sky, where to go to find it, you can only go to -cpthe designated place to find.

Continued use javacommand to perform there is a sinkhole, in a UNIX environment and the Windows environment is different, to say in a UNIX environment:

java -cp junit-3.8.2.jar:. Main

Colon :-separated paths, .representatives but also in the current directory lookup, and the second javacommand Mainrepresentative told the JVM from Mainclasses start the program, then the Mainclass where to find it? Only from -cplooking (ie the specified path .represents the current directory), JVM run Maintime finding references ActiveTestSuiteclass, continue -cpto find the specified path.

There is a sinkhole above command, execute git bash will complain in Windows's execution. Although seemingly execute a command in the git bash, but -cpthe path behind or be handed over to the Windows version of javathe executable program to resolve, and the separator in the path of the Windows version classpath is to use a semicolon ;instead of a colon :, but if you simply colon replaced by a semicolon or not, because the UNIX environment will use semicolons to separate commands (execute bash in what mkdir testDir; cd testDirtry to know), so be coupled with single quotation marks ' 'to indicate the path argument does not make any parameter analysis, as is to Javacommand.

java -cp 'junit-3.8.2.jar;.' Main

Three, Java fork in a child process

java-fork-process/working-directory/run.sh:

#!/usr/bin/env sh
echo "AAA is: $AAA"
ls -alth

java-fork-process/Fork.java:

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

public class Fork {
    public static void main(String[] args) throws Exception {
        // 使用Java代码fork一个子进程,将fork的子进程的标准输出重定向到指定文件:工作目录下名为output.txt的文件
        // 工作目录是项目目录下的working-directory目录(可以用getWorkingDir()方法得到这个目录对应的File对象)
        // 传递的命令是sh run.sh 假设working-directory目录下存在 run.sh 脚本文件
        // 环境变量是AAA=123

        // 1.可执行程序 2.参数
        ProcessBuilder pb = new ProcessBuilder("sh", "run.sh");
        // 3.工作目录
        pb.directory(getWorkingDir());
        // 4.环境变量
        Map<String, String> env = pb.environment();
        env.put("AAA", "123");
        env.get("AAA");
        pb.redirectOutput(getOutputFile());
        pb.start().waitFor();
    }

    private static File getWorkingDir() {
        Path projectDir = Paths.get(System.getProperty("user.dir"));
        return projectDir.resolve("working-directory").toFile();
    }

    private static File getOutputFile() {
        return new File(getWorkingDir(), "output.txt");
    }
}

reference:

  1. Summary linux local variables, global variables, shell variables
  2. Linux foundation - rights management chmod command
  3. "Linux Command-Line Encyclopedia"

Guess you like

Origin www.cnblogs.com/nicholaswang/p/11464784.html