在C语言中,execvp函数的输出结果通常比较难以阅读和使用。为了更好地处理这些输出结果,我们可以对其进行格式化。
以下是一个示例代码,演示了如何将execvp的输出结果格式化:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv) {
char *args[] = {"ls", "-l", "-a", NULL};
int pid, status;
int p[2];
pipe(p);
if ((pid = fork()) < 0) {
perror("fork() error");
exit(1);
}
else if (pid == 0) {
close(p[0]);
dup2(p[1], 1);
execvp(args[0], args);
perror("execvp() error");
exit(1);
}
else {
close(p[1]);
wait(&status);
if (WIFEXITED(status)) {
char buffer[1024];
int n;
while ((n = read(p[0], buffer, sizeof(buffer))) > 0) {
for (int i = 0; i < n; i++) {
if (buffer[i] == '\n') {
printf("\n");
}
else {
printf("%c", buffer[i]);
}
}
}
}
}
return 0;
}
在此示例中,我们使用了pipe函数来创建一个管道,将execvp的输出结果传输到父进程。然后,在父进程中,我们使用read函数逐个字符地读取管道中的输出结果,并根据需要格式化输出。在此示例中,我们将'\n'字符替换为换行符,以使输出更易于阅读。
需要注意的是,这只是一个示例,实际的输出格式化过程可能会更加复杂,具体取决于您的需求和要处理的输出结果。