简体   繁体   English

用C程序替换pipe-shellscript

[英]Replace pipe-shellscript with C-program

I have the following Bash script: 我有以下Bash脚本:

cat | command1 | command2 | command3

The commands never change. 命令永远不会改变。

For performance reasons, I want to replace it with a small C-program, that runs the commands and creates and assings the pipes accordingly. 出于性能原因,我想用一个小的C程序替换它,该程序运行命令并相应地创建和分配管道。

Is there a way to do that in C? 有没有办法在C中做到这一点?

As others said, you probably won't get a significant performance benefit. 正如其他人所说,您可能不会获得明显的性能优势。
It's reasonable to assume that the commands you run take most of the time, not the shell script gluing them together, so even if the glue becomes faster, it will change almost nothing. 可以合理地假设您运行的命令大部分时间都在使用,而不是将外壳脚本将它们粘合在一起,因此即使胶合速度变快,它几乎也不会改变。

Having said that, if you want to do it, you should use the fork() , pipe , dup2() and exec() functions. 话虽如此,如果您想这样做,则应该使用fork()pipedup2()exec()函数。
fork will give you multiple processes. fork将为您提供多个过程。
pipe will give you a pair of file descriptors - what you write into one, you can read from the other. pipe将为您提供一对文件描述符-您写入的文件描述符可以从另一个文件描述符读取。 dup2 can be used to change file descriptor numbers. dup2可用于更改文件描述符号。 You can take one side of a pipe and make it become file descriptor 1 (stdout) in one process, and the other side you'll make file descriptor 0 (stdin) in another (don't forget to close the normal stdin, stdout first). 您可以在一个进程中使用管道的一侧并将其变为文件描述符1(stdout),而在另一进程中将其变为文件描述符0(stdin)(不要忘记关闭普通的stdin,stdout)第一)。
exec (or one of its variants) will be used to execute the programs. exec (或其变体之一)将用于执行程序。

There are lots of details to fill in. Have fun. 有很多细节需要填写。玩得开心。

Here is an example that does pretty much this. 这是一个完成此任务的示例

There is no performance benefit for the processing itself, just a couple of milliseconds in initialization. 处理本身没有性能优势,初始化只有几毫秒。 Obviously we don't know the context in which you're doing this, but just using dash instead of bash would probably have gotten you 80% of those milliseconds from a single character change in your #! 显然,我们不知道执行此操作的上下文,但是仅使用dash代替bash可能会使您#!的单个字符更改获得80%的毫秒数#!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM