繁体   English   中英

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

[英]execve and pipe issues - how to read last output?

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

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

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

暂无
暂无

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

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