英文:
Can I use popen() without calling the shell? in C++
问题
I want to call an rpm command with flags, from my C++ code and get the output, but I don't want to use shell in the process.
I think about using popen, but saw it uses shell to execute command which I don't want.
I can use the pipe/fork/exec long method, but I want to read line by line and not sure how to do it with it, so I thought of using popen() instead if it's possible to exec with it without a middle shell.
My question is if there is a way to use popen() without it calling the shell and just invoke the binary provided itself with its flag (for example /usr/bin/rpm -qa)?
or I will have to go with the long route?
英文:
I want to call an rpm command with flags, from my C++ code and get the output, but I don't want to use shell in the process.
I think about using popen, but saw it uses shell to execute command which I don't want.
I can use the pipe\fork\exec long method, but I want to read line by line and not sure how to do it with it, so I thought of using popen() instead if it's possible to exec with it without a middle shell.
My question is if there is a way to use popen() without it calling the shell and just invoke the binary provided itself with it's flag (for example /usr/bin/rpm -qa)?
or I will have to go with the long route?
答案1
得分: 5
这里唯一的两个选项确实是要么使用popen
,要么使用pipe
+fork
+exec
。这是在Linux上运行程序并捕获其输出的唯一选择。就是这样,没有其他可能性。在Linux上,所有系统和C库调用都有公开可用的文档,没有其他选项。
从理论上讲,popen
的实现可以解析命令并确定是否包含任何shell通配符或特殊字符;如果不包含,则将其拆分成单词并exec
生成的程序。popen
是否这样做可以通过在strace
下使用-f
标志运行简单测试,查看由生成的子进程实际执行了什么来确定。
但即使你自己发现你当前的glibc这样做,这当然也不能保证它将来一直以这种方式工作。
英文:
The only two options here are, indeed, either to use popen
, or pipe
+fork
+exec
. These are the only options on Linux for running a program and capturing its output. That's it, there are no other possibilities. All system and C library calls on Linux have publicly available documentation, and there's nothing else.
It's theoretically possible for a popen
implementation to parse the command and determine whether it contains any shell wildcards or special characters; if not then split it into words and exec
the resulting program. Whether or not popen
does that can be determined by running a simple test for this under strace
with the -f
flag, and seeing what actually gets executed by the spawned child process.
But even if you discover, yourself, that your current glibc does this, this not a guarantee, of course, that it will always work this way in the future.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论