我试图执行以下命令并读取其输出。

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


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

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);

最佳答案

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

07-24 09:46
查看更多