简体   繁体   English

在C中模拟Shell命令行

[英]Emulate shell command line in C

I want to emulate the following shell command line in C, with execl(): 我想用execl()在C中模拟以下shell命令行:

find . -type f -ls | cut -d " " -f 3- | sort -n -k 6 >file.txt ; less <file.txt

I wrote each of them as: 我把它们写成:

execl("/usr/bin/find", "find", ".", "-type", "f", "-ls", (char *)NULL);
execl("/usr/bin/cut", "cut", "-d", "" "", "-f", "3-", (char *)NULL);
execl("/usr/bin/sort", "sort", "-n", "-k", "6", ">file.txt", (char *)NULL);
execl("/usr/bin/less", "less", "<file.txt", (char *)NULL);

I also implemented the pipelines but I am getting an error: 我也实现了管道,但出现错误:

cut: cut: -: Input/Output error -: Input/output error

Any idea what it means? 知道这意味着什么吗? Thanks 谢谢

All redirections, be them pipes ( | ) or redirection to files ( < , << , > , >> , etc.) are only processed by the shell. 所有重定向,无论是管道( | )还是重定向到文件( <<<>>>等)都仅由外壳程序处理。 When you pass them in an execx call, they are simply passed as an additional argument to the new program. 当您在execx调用中传递它们时,它们只是作为附加参数传递给新程序。

And anyway, execl replaces the original program by the new one, so anything after execl in never executed unless execl returned an error. 而且无论如何, execl用新程序替换原始程序,因此execl之后的任何东西都不会执行,除非execl返回错误。 The correct way is to setup pipes for the inter process communications, fork to get the number of processes, redirect standard io to the pipes, and only then exec the new programs. 正确的方法是为进程间通信设置管道,分叉以获取进程数,将标准io重定向到管道,然后才执行新程序。

This: 这个:

 "" ""

does not create a string holding a double-quoted string. 不创建包含双引号字符串的字符串。 It creates an empty string, by concatenating one empty string (the first "" pair) with another empty string (the second "" pair). 它通过将一个空字符串(第一对"" )与另一个空字符串(第二对"" )连接来创建一个空字符串。 Remember that C automatically concatenates adjacent double-quoted string literals ( "foo" "bar" is the same as "foobar" ). 请记住,C自动连接相邻的双引号字符串文字( "foo" "bar""foobar"相同)。

The quotes shouldn't be passed to cut , anyways. 无论如何,不​​应将引号传递给cut You meant: 你的意思是:

" "

Update: On the other hand, it's quite possible that you shouldn't be quoting this space after all. 更新:另一方面,您很可能根本不应该引用该空间。 The exec() family of functions don't go through a shell by default, and the quoting is for the shell. exec()系列函数默认情况下不会通过外壳,而引号是针对外壳的。 You really want to pass a space to cut , so you should do so directly with " " . 您确实想传递一个cut的空间,因此应该直接用" "

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

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