| 1 | #!/usr/bin/env bash
|
| 2 | #
|
| 3 | # Usage:
|
| 4 | # ./child-state.sh <function name>
|
| 5 |
|
| 6 | set -o nounset
|
| 7 | set -o pipefail
|
| 8 | set -o errexit
|
| 9 |
|
| 10 | self-fd() {
|
| 11 | ### C program that prints its own file descriptor state
|
| 12 | #
|
| 13 | # Similar to ls -l, but it doesn't require another process.
|
| 14 |
|
| 15 | cat << 'EOF'
|
| 16 | #include <errno.h>
|
| 17 | #include <dirent.h>
|
| 18 | #include <unistd.h>
|
| 19 | #include <stdio.h>
|
| 20 | #include <string.h>
|
| 21 |
|
| 22 | int main() {
|
| 23 | printf("pid %d\n", getpid());
|
| 24 |
|
| 25 | errno = 0;
|
| 26 | off_t pos = lseek(100, 0, SEEK_CUR);
|
| 27 | if (pos == -1) {
|
| 28 | printf("lseek: FD 100 is NOT open (errno: %d)\n", errno);
|
| 29 | } else {
|
| 30 | printf("lseek: FD 100 IS open (position: %ld)\n", pos);
|
| 31 | }
|
| 32 |
|
| 33 | DIR *d = opendir("/proc/self/fd");
|
| 34 | struct dirent *e;
|
| 35 | char path[256], target[256];
|
| 36 |
|
| 37 | while ((e = readdir(d))) {
|
| 38 | if (e->d_name[0] == '.') continue;
|
| 39 |
|
| 40 | snprintf(path, sizeof(path), "/proc/self/fd/%s", e->d_name);
|
| 41 | ssize_t len = readlink(path, target, sizeof(target) - 1);
|
| 42 |
|
| 43 | if (len != -1) {
|
| 44 | target[len] = '\0';
|
| 45 | printf("%s -> %s\n", e->d_name, target);
|
| 46 | }
|
| 47 | }
|
| 48 |
|
| 49 | closedir(d);
|
| 50 | return 0;
|
| 51 | }
|
| 52 | EOF
|
| 53 | }
|
| 54 |
|
| 55 | compare-shells() {
|
| 56 | local osh_cpp=_bin/cxx-dbg/osh
|
| 57 | ninja $osh_cpp
|
| 58 |
|
| 59 | self-fd > _tmp/self-fd.c
|
| 60 | gcc -o _tmp/self-fd _tmp/self-fd.c
|
| 61 | chmod +x _tmp/self-fd
|
| 62 |
|
| 63 | local -a shells=(bash dash mksh zsh bin/osh $osh_cpp)
|
| 64 |
|
| 65 | for sh in ${shells[@]}; do
|
| 66 | echo
|
| 67 | echo "---- $sh ----"
|
| 68 | echo
|
| 69 |
|
| 70 | # Hm I'm not seeing descriptor 100 open here?
|
| 71 | #
|
| 72 | # Note: Bug #2068, the descriptor leak in fd_state::_Open() was not
|
| 73 | # reproduced here
|
| 74 | #
|
| 75 | # See test/bug-2068.sh instead
|
| 76 |
|
| 77 | #$sh -c '_tmp/self-fd >/dev/null 1>&2; echo done'
|
| 78 | $sh -c '
|
| 79 | echo "shell pid $$"
|
| 80 | _tmp/self-fd
|
| 81 | echo done
|
| 82 | '
|
| 83 | done
|
| 84 | }
|
| 85 |
|
| 86 | "$@"
|