进程可以创建额外的 shell 可重定向文件描述符吗?
例如,进程“foo”是否可以以 bash shell 内可以执行的方式写入文件描述符 3,
foo 1>f1 2>f2 3>f3
如果可以,您将如何编写它(用 C 语言)?
Can a process 'foo' write to file descriptor 3, for example, in such a way that inside a bash shell one can do
foo 1>f1 2>f2 3>f3
and if so how would you write it (in C)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你可以这样开始你的命令:
然后如果你 ls -l /proc/_pid_of_foo_/fd 你会看到文件描述符被创建,你可以通过例如写入它们:
如果你检查文件描述符,也许会少一些黑客首先(使用 fcntl?)。
You can start your command with:
Then if you ls -l /proc/_pid_of_foo_/fd you will see that file descriptors are created, and you can write to them via eg.:
It would be less hacky perhaps if you checked the file descriptor first (with fcntl?).
shell 在执行程序之前打开程序的文件描述符。只需像使用任何其他文件描述符一样使用它们,例如
write(3, buf, len);
等。您可能需要进行错误检查以确保它们实际上已打开(尝试复制它们,然后关闭重复项将是一项简单的检查)。
The shell opens the file descriptors for your program before executing it. Simply use them like you would any other file descriptor, e.g.
write(3, buf, len);
etc. You may want to do error checking to make sure they were actually opened (attempting todup
them then closing the duplicate would be one easy check).不会。
文件描述符由 shell 打开,子进程继承它们。打开这些命令行可访问文件描述符的不是子进程,而是 bash 进程。
可能有一种方法可以说服 bash 代表进程打开其他文件描述符。这不能移植到其他 shell,而且我不确定是否存在某种机制——我只是猜测。
关键是您不能通过以特殊方式对子进程进行编码来做到这一点。外壳必须满足你的愿望。
No.
The file descriptors are opened by the shell and the child process inherits them. It is not the child process which opens these command-line accessible file descriptors, it is the bash process.
There might be a way to convince bash to open additional file descriptors on behalf of the process. That wouldn't be portable to other shells, and I'm not sure if a mechanism even exists -- I am just speculating.
The point is that you can't do this from coding the child process in a special way. The shell would have to abide your desires.
我不确定你到底在追求什么,但无论它是什么,起点都是
man dup
/man dup2
- 这是 shell 如何从随机文件描述符中生成具有给定编号的文件描述符的方式。但显然,进程 foo 必须以某种方式知道它可以写入文件描述符 3。POSIX 仅指定 0、1 和 2:shell 确保启动的任何内容都会获取应用程序中的文件描述符和 libc。上下文还期望它们是 stdin/stdout/stderr。从 3 开始及以后 - 由应用程序开发人员决定。
I'm not sure what you are precisely after, but whatever it is, starting point going to be the
man dup
/man dup2
- this is how the shells make out of a random file descriptor a file descriptor with given number.But obviously, the process
foo
has to know somehow that it can write to the file descriptor 3. POSIX only specifies 0, 1 and 2: shell ensures that whatever is started gets the file descriptors and libc in application's context also expects them to be the stdin/stdout/stderr. Starting from 3 and beyond - is up to application developer.