Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
lua-spawn/examples/pipes.lua
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
executable file
39 lines (38 sloc)
1.68 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env lua | |
| --[[ | |
| This example shows off using lunix to create pipes for the child process | |
| ]] | |
| local posix_spawn = require "spawn.posix" | |
| local unix = require "unix" | |
| local read, write, pid do | |
| -- file_actions is an ordered list of operations to do before the child process starts | |
| -- you can add operations to it such as `open()`, `dup2()` and `close()` | |
| local file_actions = assert(posix_spawn.new_file_actions()) | |
| -- Create two pipes, one for stdin, one shared by stdout and stderr | |
| -- the first fd returned by pipe() can only be read from | |
| -- the second fd returned by pipe() can only be written to | |
| -- "e" means to enable O_CLOEXEC (this way the other ends of the pipes are closed in the child) | |
| local child_stdin, child_stdout | |
| child_stdin, write = assert(unix.fpipe("e")) | |
| read, child_stdout = assert(unix.fpipe("e")) | |
| -- Tell posix_spawn to dup `child_stdin` to fd 0 in the child | |
| assert(file_actions:adddup2(unix.fileno(child_stdin), 0)) | |
| -- Tell posix_spawn to dup `child_stdout` to fd 1 in the child | |
| assert(file_actions:adddup2(unix.fileno(child_stdout), 1)) | |
| -- Tell posix_spawn to dup fd 1 (which is child_stdout already) to fd 2 (stderr) | |
| assert(file_actions:adddup2(1, 2)) | |
| -- Start the child program: cat | |
| pid = assert(posix_spawn.spawnp("cat", file_actions, nil, {"cat"}, nil)) | |
| -- Close files now owned by the child | |
| child_stdin:close() | |
| child_stdout:close() | |
| end | |
| -- Lets write a string to the child | |
| assert(write:write("foo")) | |
| assert(write:flush()) | |
| -- The child is 'cat': we should be able to read "foo" back | |
| print(read:read(3)) | |
| -- Close the child's stdin. For 'cat' this should result in the program exiting | |
| write:close() | |
| -- Wait for child to exit and print the exit status | |
| print(unix.waitpid(pid)) |