7.10 创建子程序

概念

  • Deno能够通过Deno.run.产生子流程。
  • --Allow-run需要权限才能产生子进程。
  • 派生的子进程不在安全沙箱中运行。
  • 通过stdin,、stdoutstderr流与子流程进行通信。
  • 使用特定的shell,提供其路径/名称和字符串输入开关,例如:Deno.run({cmd:[“bash”,“-c”,‘“ls-la”’]});

简单例子

此示例相当于从命令行运行命令‘ECHO hello’

/**
 * subprocess_simple.ts
 */

// create subprocess
const p = Deno.run({
  cmd: ["echo", "hello"],
});

// await its completion
await p.status();

运行它:

$ deno run --allow-run ./subprocess_simple.ts
hello

安全

创建子流程需要有--Allow-run权限。请注意,子进程不在Deno沙箱中运行,因此具有与您自己从命令行运行命令相同的权限。

和子程序通信

默认情况下,使用Deno.run()时,子进程会继承父进程的stdinstdoutstderr。如果您想与Started子进程通信,可以使用“Piped”选项。

/**
 * subprocess.ts
 */
const fileNames = Deno.args;

const p = Deno.run({
  cmd: [
    "deno",
    "run",
    "--allow-read",
    "https://deno.land/std@0.95.0/examples/cat.ts",
    ...fileNames,
  ],
  stdout: "piped",
  stderr: "piped",
});

const { code } = await p.status();

// Reading the outputs closes their pipes
const rawOutput = await p.output();
const rawError = await p.stderrOutput();

if (code === 0) {
  await Deno.stdout.write(rawOutput);
} else {
  const errorString = new TextDecoder().decode(rawError);
  console.log(errorString);
}

Deno.exit(code);

当你运行它:

$ deno run --allow-run ./subprocess.ts <somefile>
[file content]

$ deno run --allow-run ./subprocess.ts non_existent_file.md

Uncaught NotFound: No such file or directory (os error 2)
    at DenoError (deno/js/errors.ts:22:5)
    at maybeError (deno/js/errors.ts:41:12)
    at handleAsyncMsgFromRust (deno/js/dispatch.ts:27:17)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容