简体   繁体   English

关于如何在Linux中与另一个Shell交互使用Shell的一些问题

[英]Some questions regarding how to use a shell interactively with another shell in linux

This post is about some automation tasks, and also to satisfy my curiosity. 这篇文章是关于一些自动化任务的,也是为了满足我的好奇心。

Is this scenario possible, can anyone offer any practical pointers? 这种情况是否可能,任何人都可以提供任何实用的指导吗?

Run a shell script 运行一个shell脚本

shell_exec(bash script);

Bash script like: Bash脚本如下:

  • Run a shell; 运行一个shell;
  • read file for input; 读取文件以供输入;
  • pass input to shell; 将输入传递给外壳;
  • fetch result from shell; 从外壳获取结果;
  • write to another file for output. 写入另一个文件以输出。
  • Keep in infinite loop. 保持无限循环。

Write input commands to file for example: 将输入命令写入文件,例如:

  • wait few seconds 等待几秒钟
  • read output file for result 读取输出文件以获取结果
  • depending on output, write new input commands to file 根据输出,将新的输入命令写入文件
  • the loop continues. 循环继续。

I'm going to leave a shameless link to a post where I demonstrate doing this, "expect in php": http://codehackit.blogspot.be/2012/04/automating-command-line-scripts-in-php.html 我将留下一个毫不客气的链接,该文章演示了执行此操作的过程,“在php中期待”: http : //codehackit.blogspot.be/2012/04/automating-command-line-scripts-in-php。 HTML

Basically it's just a wrapper around proc_open(), which returns FDs for writing and reading to another processes stdin/stdout. 基本上,它只是proc_open()的包装,它返回用于写入和读取到另一个进程stdin / stdout的FD。 http://php.net/manual/en/function.proc-open.php http://php.net/manual/en/function.proc-open.php

In order to avoid problems with partial reads and writes (due to io buffering and races), you may want to consider using a directory the in/out-box like so: 为了避免部分读写问题(由于io缓冲和竞争),您可能需要考虑使用类似in / out-box的目录:

  1. Create your command files in the dir with "temporary" names (eg "cmd_`date +%s`.txt.tmp") 在目录中使用“临时”名称创建命令文件(例如,“ cmd_`date +%s`.txt.tmp”)
  2. When you're done writing to a given command file, close it (to flush the buffers), then rename it to remove the ".tmp". 完成对给定命令文件的写入后,将其关闭(以刷新缓冲区),然后重命名以删除“ .tmp”。 Rename is atomic within a filesystem. 重命名在文件系统中是原子的。
  3. Have the consuming bash "daemon" only look at "cmd_*.txt" (not .tmp) and when it's done with a given command, either delete the cmd file or rename it to give it a ".done" suffix. 让耗用bash的“守护程序”仅查看“ cmd _ *。txt”(不是.tmp),并且在使用给定命令完成操作后,请删除cmd文件或将其重命名为后缀“ .done”。 (If you need multiple parallel worker daemons, you can probably even rename to ".processing" to "claim" a cmd while you work on it. Just be sure to check the return code of the rename when you do so to see if another worker out-raced you.) (如果需要多个并行工作程序守护程序,则甚至可以在处理cmd时将其重命名为“ .processing”来“声明” cmd。只需确保检查重命名的返回码以查看是否有另一个工人胜过您。)

Do likewise for the output files. 对输出文件也同样如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM