Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.73 KB | None | 0 0
  1. Node.js でサブプロセス起動して終了する
  2.  
  3. **[parent.js]**
  4. ```js
  5. const cp = require("child_process")
  6.  
  7. const sp = cp.fork("./child.js", [], { detached: true })
  8.  
  9. sp.send("AAA")
  10.  
  11. sp.on("message", value => {
  12. console.log(value)
  13.  
  14. sp.disconnect()
  15. sp.unref()
  16. })
  17.  
  18. console.log("PID", process.pid)
  19. ```
  20.  
  21. **[child.js]**
  22. ```js
  23. const fs = require("fs")
  24.  
  25. const log = data => fs.appendFileSync("log.txt", String(data) + "\n")
  26.  
  27. let n = 0
  28. const t = setInterval(() => {
  29. log(n++)
  30. if(n > 3) clearInterval(t)
  31. }, 2000)
  32.  
  33. process.on("message", value => {
  34. log("message: " + value)
  35. process.send("BBB")
  36. })
  37.  
  38. log("[start] pid: " + process.pid)
  39. ```
  40.  
  41. `parent.js` のログ
  42.  
  43. ```
  44. PID 9840
  45. BBB
  46. ```
  47.  
  48. `child.js` のログ
  49.  
  50. ```
  51. [start] pid: 9820
  52. message: AAA
  53. 0
  54. 1
  55. 2
  56. 3
  57. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement