ProcessBuilder执行Shell脚本 #!/bin/bash 怎么弄守护进程
时间: 2023-08-04 13:05:31 浏览: 261
如果你要使用ProcessBuilder来执行一个Shell脚本,并且希望将其作为守护进程运行,可以尝试以下方法:
1. 在Shell脚本中添加守护进程代码,例如使用nohup命令将脚本转换为守护进程,例如:
```
nohup your_script.sh &
```
2. 在ProcessBuilder中设置Shell脚本的工作目录,并在Shell脚本中设置守护进程。例如:
```java
ProcessBuilder pb = new ProcessBuilder("/bin/bash", "/path/to/your_script.sh");
pb.directory(new File("/path/to/working/directory"));
Process p = pb.start();
```
请注意,这种方法需要在Shell脚本中自行实现守护进程,否则将无法达到预期的效果。
相关问题
ProcessBuilder执行Shell脚本, Shell脚本怎么弄守护进程等方式来保证持续执行
要让Shell脚本作为守护进程持续执行,你可以在Shell脚本中使用循环语句,并让循环一直执行下去。例如,在Shell脚本中使用`while`循环来让脚本持续执行:
```
#!/bin/bash
while true; do
# your commands here
sleep 10 # 休眠10秒钟
done
```
在上面的例子中,`while`循环将一直执行,直到被手动停止。在`while`循环中,你可以添加需要执行的命令,并使用`sleep`命令来让脚本休眠一段时间。
在Java中执行这个Shell脚本时,你可以使用以下代码:
```
ProcessBuilder pb = new ProcessBuilder("/bin/bash", "/path/to/your/script.sh");
pb.inheritIO();
Process process = pb.start();
```
这样,你就可以在Java中启动一个Shell脚本作为守护进程,让它持续执行。
springboot怎么动态生成shell.sh Linux命令脚本 并且执行
在 Spring Boot 中,可以使用 `ProcessBuilder` 类动态生成并执行 Shell 脚本。以下是一个简单的示例:
```java
@RestController
public class ShellController {
@GetMapping("/executeShell")
public String executeShell() throws IOException {
String script = "#!/bin/bash\n" +
"echo \"Hello World!\"\n" +
"ls -la\n";
File file = File.createTempFile("script", ".sh");
file.setExecutable(true);
FileUtils.writeStringToFile(file, script, StandardCharsets.UTF_8);
ProcessBuilder processBuilder = new ProcessBuilder(file.getAbsolutePath());
Process process = processBuilder.start();
int exitCode = process.waitFor();
return "Exit code: " + exitCode;
}
}
```
在上面的示例中,我们使用 `File.createTempFile` 方法创建一个临时文件,并将 Shell 脚本写入该文件中。然后,我们使用 `ProcessBuilder` 类创建一个新的进程,并指定要执行的 Shell 脚本文件。最后,我们调用 `Process.waitFor` 方法等待进程执行完毕,并获取退出码。
注意,需要在 Linux 系统上安装 Bash 解释器,才能执行 Shell 脚本。如果没有安装 Bash,可以将 Shell 脚本中的 `#!/bin/bash` 改为 `#!/bin/sh`,使用系统默认的 Shell 解释器。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)