我正在使用Ubuntu 11.10。如果我打开终端并调用: ps all
我会将结果截断(即每行最多 100 个字符)转换为终端窗口的大小。
如果我打电话给ps all > file
这些行不会被截断,所有信息都在文件中(有一行有 ~200 个字符)
在 C 中,我试图实现相同的目标,但行被截断了。
我试过
了 int rc = system("ps all > file");
以及 popen 的变体。
我假设系统(和 popen)使用的 shell 默认每行的输出为 80,如果我使用 popen 解析它是有意义的,但由于我将其管道传输到文件,我希望它忽略外壳的大小,就像我在 shell 中执行此操作时所经历的那样。
博士如何确保从 C 应用程序调用时ps all > file
不会截断行?
作为解决方法,请尝试在调用ps
时传递-w
或可能-ww
。
从手册页 (BSD):
-w Use 132 columns to display information, instead of the default which is your
window size. If the -w option is specified more than once, ps will use as many
columns as necessary without regard for your window size. When output is
not to a terminal, an unlimited number of columns are always used.
Linux:
-w Wide output. Use this option twice for unlimited width.
或者
您可能会自己做一个fork/exec/wait
而不是使用system
;为了简洁起见,省略了错误处理:
#include <unistd.h>
#include <stdio.h>
pid_t pid = fork();
if (!pid) {
/* child */
FILE* fp = fopen("./your-file", "w");
close(STDOUT_FILENO);
dup2(fileno(fp), STDOUT_FILENO);
execlp("ps", "ps", "all", (char*)NULL);
} else {
/* parent */
int status;
wait(&status);
printf("ps exited with status %dn", status);
}