c - execve 和管道问题 - 如何读取最后的输出?

标签 c macos pipe execve

我正在尝试执行以下命令并读取它的输出。

/usr/sbin/system_profiler SPHardwareDataType | grep 'Serial Number'

我必须直接使用execve(没有popen)。我相信我在最后一步失败了,将第二个 child 的输出读入 parent 的缓冲区。我收到“阅读问题”消息。

char *cmd1[] = {"system_profiler", "SPHardwareDataType", 0};
char *cmd2[] = {"grep", "'Serial Number'", 0};
pid_t pid;
int pipe1[2];
int pipe2[2];
int ret;

pipe(pipe1);

// first child
pid = fork();
if (pid < 0) {
 return;
}

if (pid == 0) {
 close(pipe1[0]); // close read-end
 dup2(pipe1[1], 1); // copy write-end over stdout
 close(pipe1[1]); // close write-end
 execve("/usr/sbin/system_profiler", cmd1, NULL);
 exit(1);
}

pipe(pipe2);

// second child
pid = fork();
if (pid < 0) {
 return;
}

if (pid == 0) {
 // handle connection between first and second child
 close(pipe1[1]); // close write-end
 dup2(pipe1[0], 0); // copy read-end over stdin
 close(pipe1[0]); // close read-end
 // handle connection between second child and parent
 close(pipe2[0]); // close read-end
 dup2(pipe2[1], 1); // copy write-end over stdout
 close(pipe2[1]); // close write-end
 execve("/usr/bin/grep", cmd2, NULL);
 exit(1);
}

close(pipe1[0]);
close(pipe1[1]);
close(pipe2[1]);

ret = read(pipe2[0], buffer, 128);
if (ret <= 0) {
 printf("Reading problem!\n");
 return;
}
buffer[ret] = '\0';
printf("Buffer: %s\n", buffer);

最佳答案

哈哈。除了我的字符串定义之外,代码是正确的。我有“字符串数字”,但引号有问题 - 我删除了它们。

关于c - execve 和管道问题 - 如何读取最后的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18061680/

相关文章:

C管道初始化错误

linux - 通过 ssh 运行程序失败并显示 "Error opening terminal: unknown."

c - 尝试运行 MPI 矩阵乘法示例

c - 在 C 中比较不同数据类型的一般规则是什么?

cocoa - 复制 Cocoa 中目录的内容但不包括子目录

macos - 如何创建可以在 OSX 中编辑 plist 的脚本

stream - pipe()将如何在节点js中执行读写操作?

linux - 如何使用 empty 与 telnet 交互

c++ - CoCreateInstance() 永远不会返回

c - `man cc` : no info about -Wall and -g flags (Learn C the Hard Way)