[英]How to pass stdout of command in system() to self stdin?
Assuming I call something like: 假设我称呼类似:
system("ls -1"); // argument minus-one puts one item per line
...how would I capture this in calling process stdin? ...我如何在调用进程stdin中捕获它?
From what I've read, system (in Linux) opens a bash-prompt and attempts to execute the command. 根据我所读的内容,系统(在Linux中)打开一个bash提示符并尝试执行命令。 This indicates the process calling system is parent.
这表明流程调用系统是父系统。 Reading about parent process pid suggest this is always
1111
, but I can't find a definite source on this, just linux haxers saying "do this" with neither explanation nor source. 阅读有关父进程pid的信息时,建议始终为
1111
,但是我找不到确切的来源,只是linux骇客说了“做这个”,既没有解释也没有来源。
Reading some other sources one can pass data to arbitrary process pipe through /proc/pid/fd/0 读取其他一些源可以通过/ proc / pid / fd / 0将数据传递到任意进程管道
Based on reading those, I would think that: 根据这些内容,我认为:
system("ls -1 > /proc/1111/fd/0");
...accomplishes this. ...完成了这一点。 But it looks like nothing I've done before and my sources for the deduction are not as formal as I'd like them to.
但这似乎是我以前没有做过的事情,我的推论来源也不像我希望的那样正式。
So, is this a portable way of passing output of system command to self stdin? 那么,这是将系统命令输出传递给self stdin的一种可移植方式吗?
If not, how would I do it? 如果没有,我该怎么办?
It seems you are trying to read the list of all file/folder names in a particular directory. 看来您正在尝试读取特定目录中所有文件/文件夹名称的列表。 In your case the current working directory.
您的情况是当前工作目录。 It also appears you are interested in a *NIX solution since you tried to use
ls
. 由于您尝试使用
ls
您似乎也对* NIX解决方案感兴趣。
There are many ways to read the output from a subprocess into the parent process. 有很多方法可以将子过程的输出读取到父过程中。 You can use
fork
/ exec
with pipes or you are use popen
. 您可以将
fork
/ exec
与管道一起使用,也可以使用popen
。
But for this example you need not go through ls
. 但是对于此示例,您无需经过
ls
。 You are directly read the directory using the Linux API. 您可以使用Linux API直接读取目录。
You need to use the functions opendir
and readdir
. 您需要使用功能
opendir
和readdir
。
Consider the following program - 考虑以下程序-
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
DIR *directory = opendir(".");
if (directory == NULL)
return EXIT_FAILURE;
struct dirent * entry;
while (entry = readdir(directory)) {
printf("%s\n", entry->d_name);
}
closedir(directory);
return 0;
}
You might want to skip the "."
您可能要跳过
"."
and ".."
entries if you don't want those. 和
".."
条目(如果您不需要这些条目)。
Here is a working demo for the same 这是相同的工作演示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.