0

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

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

1 回答 1

0

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

于 2013-08-05T16:50:57.453 回答