Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C on Linux, popen / system to "ps all > file" truncates all lines to 80 characters

I'm using Ubuntu 11.10. If I open a terminal and call: ps all I get the results truncated (i.e. 100 characters at most for each line) to the size of the terminal window.
If I call ps all > file The lines don't get truncated and all the information is in the file (There is a line that has ~200 characters)

In C, I am trying to achieve the same but the lines get truncated.
I've tried
int rc = system("ps all > file"); as well as variants of popen.
I assume the shell being used by system (and popen) defaults the output of each line to 80, which make sense if I were to parse it using popen, but since I am piping it to a file I expect it to disregard the size of the shell like I experienced when doing it in my shell.

TL;DR
How can I make sure ps all > file doesn't truncate lines when called from C application?

like image 281
Chen Harel Avatar asked Apr 24 '12 12:04

Chen Harel


1 Answers

As a workaround, try passing -w or possibly -ww to ps when you invoke it.

From the man page (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.

Alternatively,

You might have some success doing a fork/exec/wait yourself instead of using system; omitting error handling for brevity:

#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);
}
like image 51
John Ledbetter Avatar answered Oct 24 '22 20:10

John Ledbetter