在Linux上的C中,popen/system到"ps all> file"会将所有行截断为80个字符

Che*_*rel 7 c c++ linux ubuntu system

我正在使用Ubuntu 11.10.如果我打开终端并打电话:ps all我将结果截断(即每行最多100个字符)到终端窗口的大小.
如果我调用ps all > file行不被截断,所有信息都在文件中(有一行有~200个字符)

在C中,我试图实现相同但线条被截断.
我尝试
int rc = system("ps all > file"); 过和popen的变种一样.
我假设系统使用的shell(和popen)将每行的输出默认为80,如果我使用popen解析它,这是有道理的,但是由于我将它传递给文件,我希望它忽略它的大小像我在shell中做的那样经历了shell.

TL; DR
如何ps all > file从C应用程序调用时确保不截断行?

Joh*_*ter 6

作为一种变通方法,尝试通过-w或可能-wwps当你调用它.

从手册页(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.
Run Code Online (Sandbox Code Playgroud)

Linux的:

-w      Wide output. Use this option twice for unlimited width.
Run Code Online (Sandbox Code Playgroud)

或者,

你可能会取得一些成功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 %d\n", status);
}
Run Code Online (Sandbox Code Playgroud)