(C) Redirecting stdout to a buffer

I'm currently authoring a python binding for a third-party application. A function of the third-party applications allows users to set the filename to "-" which will then print the result to stdout. I'd like to be able to catch that output into a buffer and handle it entirely in memory rather than creating a temporary file on disk (that's why freopen does not fit for this). Can someone give me a hint?

POSIX is fine. It may be great to have a platform-independent way for doing this, but I found my solution with glibc's open_memstream().

Similar Messages

  • Redirecting stdout in 64 bit mode

    Hi,
    I have a problem. I wanted to redirect stdout to a text file and back. In 32 bit mode everything works fine using file member to struct FILE, but in 64 bit mode only data member FILE has long _pad[16]. Can anyone tell me how to use this to redirect stdout to file and visevesra. Thanks in advance.
    Amandeep

    By default in 10.6.8 it should be in 64 bit mode but to check and change it in Finder highlight Aperture, the application, and go command I to open the info window and look about 1/4 of the way down
    (Note this is from Lion so it is slightly different then what you will see)

  • Redirecting stdOut to a JTextArea - Help!

    I want to redirect stdOut via System.setOut to a JTextArea - I'm most of the way there but I keep getting some strange errors. I'd really appreciate some help!
    I have a class called MainDebug which in its constructor calls
    System.setOut(new DebugStream((OutputStream)System.out));
    it also has a method
    public void appendMessage(String message)
    txtAreaDebug.append(message);
    where txtAreaDebug is the JTextArea to which I want to redirect stdOut.
    In MainDebug is another class called DebugStream (which is referred to in MainDebug's constructor). The entirety of that class is as follows:
    public class DebugStream extends java.io.PrintStream
    public void println(String x)
    MainDebug.this.appendMessage(x);
    public void write(int x)
    MainDebug.this.appendMessage(new Integer(x).toString());
    When I build I get these errors:
    pcgen\gui\MainDebug.java:63: cannot resolve symbol
    symbol : constructor DebugStream (java.io.OutputStream)
    location: class pcgen.gui.MainDebug.DebugStream
    System.setOut(new DebugStream((OutputStream)System.out));
    ^
    pcgen\gui\MainDebug.java:166: cannot resolve symbol
    symbol : constructor PrintStream ()
    location: class java.io.PrintStream
    public class DebugStream extends java.io.PrintStream
    For the first error, shouldn't DebugStream inherit the proper constructor from PrintStream? And I have no clue about the second error - I believe I've extended the class correctly.
    Pearls of wisdom appreciated! :)

    Constructors aren't inherited from superclasses, so you'll need to supply your own constructor for DebugStream.
    FWIW, I've done this before and here's my version of DebugStream:
       private class MyPrintStream extends PrintStream
          public MyPrintStream(OutputStream pOut)
             super(pOut);
          public void println(String pString) {
             if (mResultsPanel != null)
                mResultsPanel.append(pString);
             super.println(pString);
          public void println(Object pObject)
             if (mResultsPanel != null)
                mResultsPanel.append(pObject.toString());
             super.println(pObject);
       }where mResultsPanel has a reference to the JTextArea.
    Good luck,
    Tom

  • Redirect stdout to null

    Hi,
    can you redirect stderr and stdout of servants to /dev/null?
    I'd like to avoid the overhead of writing to the stdout files.
    Thanks,
    Juergen

    Hi,
    probably you can try the two options in each server's command line option:
    http://edocs.bea.com/tuxedo/tux100/rf5/rf5.html#wp1003290
    [-e stderr_file]
    [-o stdout_file]

  • Redirecting stdout of third party API?

    Good Morning (or afternoon),
    I have an interesting problem with an application that I am writing.
    I am using my own classes, as well as a third party package that somebody developed, in this application.
    I have developed a GUI for ease of use and in this GUI I have a textarea component that shows all stdout messages.
    To achieve this I simply used System.setOut(PrintStream out) to redirect the output to my textarea. Now, all stdout messages display on my textarea. So far so good.
    The problem came when I used the third party package. The third party stdout still goes to the default (terminal).
    I have to use the third party package through it's main method so I am calling ThirdPartyPackage.main(thingToPass).
    Does anyone know why this occurs, or how I can get the third party classes to use the stdout that is currently in use by the calling class?
    I am very stuck and would really appreciate any help even theoretical.
    Thankyou in advance.

    I am doing exactly the same thing, here's the code that calls an external process and appends the output to a JTextArea:
    (txtOutput is the JTextArea I'm showing the output in)
              try
                   Process proc = Runtime.getRuntime().exec(progName);
                   InputStream procStdout = proc.getInputStream();
                   InputStream procStderr = proc.getErrorStream();
                   int exit = 0;
                   boolean processEnded = false;
                   while(!processEnded)
                        try
                             exit = proc.exitValue();
                             processEnded = true;
                        catch(IllegalThreadStateException e) {} // still running
                        int n = procStdout.available();
                        if(n > 0)
                             byte[] pbytes = new byte[n];
                             procStdout.read(pbytes);
                             //System.out.print(new String(pbytes));
                             //System.out.flush();
                             txtOutput.append(new String(pbytes));
                             txtOutput.setCaretPosition(txtOutput.getText().length());
                        n = procStderr.available();
                        if(n > 0)
                             byte[] pbytes = new byte[n];
                             procStderr.read(pbytes);
                             System.err.print(new String(pbytes));
                             System.err.flush();
                        try
                        Thread.sleep(10);
                        catch(InterruptedException e) {}
                   System.out.println();
                   System.out.println("Process exited with: " + exit);
              catch (java.io.IOException e)
                   System.out.println(e.toString());
              }

  • Redirecting stdout and stderr when starting a MS with the NM

    We are looking at using the Node Manager for stopping and starting the managed servers in some of our projects, to give the testers/developers the ability with operator role in the WLS console to save them calling someone.
    The only trouble is, with our existing shell start scripts we redirect shell level stdout and stderr to a file, i.e
    nohup ./startManagedWebLogic.sh test1-ms11 >> $OUTFILE 2>&1 &
    But how do you do the same when starting the same managed server using the node manager and the WLS Admin Console??
    There is the argument "-Dweblogic.log.RedirectStdoutToServerLogEnabled=true", but this only redirects on the JVM level.
    Is there a way around this problem to get the node manager outputing the same as our scripts do.
    Any direction would be great.
    Alistair.

    Gene
    Thanks for the replies and additional information.
    I was almost sure that one of the previously suggested troubleshooting steps would solve the problem but unfortunately that was not the case.
    So, let us look at the following factors....
    1. Delete the Adobe Premiere Elements Prefs file and, if that does not work, then delete the whole 12.0 Folder in which the Adobe Premiere Elements Prefs file exists.
    Local Disk C
    Users
    Owner
    AppData
    Roaming
    Adobe
    Premiere Elements
    12.0
    and in the 12.0 Folder is the Adobe Premiere Elements Prefs file that you delete. If that does not work, then you delete the whole 12.0 Folder in which the Adobe Premiere Elements Prefs file exists. Be sure to be working with Folder Option Show Hidden Files, Folders, and Drives active so that you can see the complete path cited.
    2. Try to open the Premiere Elements 12 Editor from its Adobe Premiere Elements.exe file rather than desktop icon which uses Adobe Premiere Elements 12.exe file.
    Local Disk C
    Program Files
    Adobe Premiere Elements 12
    and in the Adobe Premiere Elements 12 Folder is the Adobe Premiere Elements.exe file that you double click to open the Premiere Elements 12 Editor bypassing the Welcome Screen. If necessary, we could create a desktop shortcut for the Adobe Premiere Elements.exe file for future use to open the program.
    Also, look at the necessity to right click the desktop icon for the program and the .exe files and apply Run As Administrator to each even if you are running the program from a User Account with Administrative Privileges.
    3. Consider creating a new User Account with Administrative Privileges and install and running Premiere Elements 12 in it (I would save this consideration for the last.)
    Please review. We will be watching for the results.
    Thank you.
    ATR

  • Stdout waiting for buffer fillup

    I am wondering how you can coax a process to output more frequently, as if it were running on a terminal or terminal window.
    Currently, any process outputting on stdout on Solaris outputs normally on a terminal device such as a xterm or a telnet session. Data is output usually when a newline is made. However that same process if run outputting to a pipe or run as a remote command through something like rsh, will output only when the output buffer is filled (which seems to be about every 4K bytes). This does not occur with stderr.
    If you don't believe me then try this simple example perl script:
    #!/usr/bin/perl
    for ($i=0; $i<=5; $i++) {
    print "$i\n";
    sleep 1;
    If you run it from the command line you get a line printed every second. If you run it through a pipe or as a remote process, you get a 5 second wait then all the lines are printed at once. Modify the program to print to STDERR instead and this problem does not occur.
    I am running into some problems with programs that run other programs. The program that is calling the other program is having to wait for the stdout 4K buffer to fill up before it receives any data.
    I understand that I can modify the source code to the program that is called and force a flush (for example in C using the fflush() library call) and the process will output more frequently, however I am trying to find a solution I can use in a calling program. I do not want to modify the program called.
    Does anyone know what can be done to coax a program to output more frequently? It is obvious that terminal emulator programs, such as xterm, are doing something, so there should be some sort of solution.
    Any help anyone has would be greatly appreciated,
    Rick Rohan

    Figured it out. I needed a pseudo-terminal. Under Perl this is the IO::Pty module.
    Rick

  • How to redirect stdout & stderr to a logfile

    Hello All,
    I'm new to java. I have to redirect all the output that get printed to a logfile (text) on my hard disk?
    Can anyone plz give me a pointer?
    thanks
    Sumanth

    He probably means this but doesnt know how to ask for it:
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/System.html
    static void setErr(PrintStream err)
    Reassigns the "standard" error output stream.
    static void setIn(InputStream in)
    Reassigns the "standard" input stream.
    static void setOut(PrintStream out)
    Reassigns the "standard" output stream.

  • Redirecting stdout and stderr to GUI

    Hello,
    Is it possible to redirect System.out and System.err output to a JTextArea or a JLabel? This output will be coming from another class that is instantiated from within my GUI class.
    Any suggestions or otherwise would be appreciated,
    Thanks.

    you need to define a PrintStream for it.
    suggest you write a class extending OutputStream and in the flush() method include the writing to the text area.
    MyOutStream outStream = new MyOutStream();
    PrintStream ps = new PrintStream(outStream.getOutStream(), true);
    System.setErr(myPrintStream);
    System.setOut(myPrintStream);
    can get messy mind you.
    hope this points you in some useful direction.
    Takis

  • WebLogic 10.3.6 logging health messages to stdout

    Hello,
    I have a 10.3.6 instance running with JRE 1.7.0_25-b15.
    The server is sending health related info messages to stdout.
    "com.bea.logging.BaseLogger log Info: XX% of the total memory in the server is free"
    2 messages are logged at a time, but not on a consistent interval.
    We send the stdout and stderr to a log file via the -Dweblogic.Stdout and -Dweblogic.Stderr properties.  These messages are adding to the
    log file size and frankly are an annoyance.  Is there any additional settings/properties/filters needed to eliminate these messages?
    These are the instance's settings with regard to logging:
    - Minimum severity to log: Warning
    - Log File Severity level: Warning
    - Standard Out Severity level: Off
    - Memory Buffer Severity level: Warning
    - Redirect Stdout Logging:  disabled
    - Redirect Stderr Logging:  disabled
    - Logging implementation:  JDK
    Thanks in advance.

    Hello,
    I have a 10.3.6 instance running with JRE 1.7.0_25-b15.
    The server is sending health related info messages to stdout.
    "com.bea.logging.BaseLogger log Info: XX% of the total memory in the server is free"
    2 messages are logged at a time, but not on a consistent interval.
    We send the stdout and stderr to a log file via the -Dweblogic.Stdout and -Dweblogic.Stderr properties.  These messages are adding to the
    log file size and frankly are an annoyance.  Is there any additional settings/properties/filters needed to eliminate these messages?
    These are the instance's settings with regard to logging:
    - Minimum severity to log: Warning
    - Log File Severity level: Warning
    - Standard Out Severity level: Off
    - Memory Buffer Severity level: Warning
    - Redirect Stdout Logging:  disabled
    - Redirect Stderr Logging:  disabled
    - Logging implementation:  JDK
    Thanks in advance.

  • Win 2008  WL 10.3.3 stdout appearing in .log and .out files

    Recently noticed a ballooning [ServerName].out file in the logs directory. In weblogic management console I do have it configured to redirect stdout and stderr to weblogic logging (.log file). Both the .log and .out file contain the same stdout/stderr information. I would like to eliminate the .out file if possible (since WL only rotates the .log), but cannot find where it is configured. The managed servers are NOT windows services (no -log option).
    Did not find any logging parameters in JAVA_OPTIONS or paramters in the startManagedSvc.cmd file.
    Is this something needing to be corrected at the application level? (log4j)

    opie wrote:
    Recently noticed a ballooning [ServerName].out file in the logs directory. In weblogic management console I do have it configured to redirect stdout and stderr to weblogic logging (.log file). Both the .log and .out file contain the same stdout/stderr information. I would like to eliminate the .out file if possible (since WL only rotates the .log), but cannot find where it is configured. The managed servers are NOT windows services (no -log option).
    Did not find any logging parameters in JAVA_OPTIONS or paramters in the startManagedSvc.cmd file.
    Is this something needing to be corrected at the application level? (log4j)Depends on what you are actually seeing in those files. Are you outputting log4j messages to a log file AND the console?
    Here is a snippet of the log4j configuration file that denotes writing to the console:
        <appender name="ConsoleAppender" class="org.apache.log4j.ConsoleAppender">
            <layout class="org.apache.log4j.PatternLayout">
                <param name="ConversionPattern" value="%d{yyyy-MM-dd hh:mm:ss} %-5p [%t] - %C{1}.%M -> %m%n" />
            </layout>
          </appender>
        <root>
            <level value="ALL" />
            <appender-ref ref="ConsoleAppender" />
        </root>Edited by: ForumKid2 on Dec 29, 2010 11:36 AM

  • Re-directing stdout to a text box

    How can we redirect stdout to a textbox?

    It's very hard to do. You have to redirect to pointers from the commandline environment to your application and it's very tedious and difficult to do smoothly. I personally spool the oiytput to a file and just read the file back and update the display from that.
    For example, if you want to display the directory output in your textbox do:
    dir >tempfile.txt
    this will append to the existing file. When the command returns read the file content, delete and repeate etc, or use:
    dir  >>tempfile.txt
    to overwrite any existing file with the new content.
    If you want to try redirecting the pointers here is a complete article I found on the subject:
    http://support.microsoft.com/kb/190351
    I gaveup on it after trying for half a day.
    Jattie van der Linde
    Engineering Manager, Software & Automation
    TEL Magnetic Solutions Ltd

  • Capturing stdout from JVM process

    Hi,
    Using JNI native methods I call functions in a shared C library from my Java program. I do not have access to the shared library source code. The shared library writes informational messages to stdout. I want to be able to capture these messages and display them in my Java GUI as they occur. I need a cross-platform solution because the Java program needs to run on both Windows and Linux.
    I have googled and searched the JavaSoft forums but I cannot find an answer to what I am trying to do. I have seen answers on how to do it if you are using Runtime.exec methods, but I am not doing that. Also, redirection on the command line will not work since I want to show these messages as they occur in my GUI.
    I have thought of redirecting stdout to a pipe in the JNI code and using select to read the bytes off the pipe. Then sending the bytes up to a Java object. All this would run in a separate thread. But this seems overly complicated.
    Any suggestions?
    charlie

    I developed a solution to this problem using named pipes. It works well on Linux (2.6 kernel) and it may work on Windows but I don't know. Example code follows. I would be most interested in any feedback on this solution or on the code itself.
    There are 2 files, StdoutRedirect.java and StdoutRedirect.c.
    1) Compile the java file and run javah on it to get StdoutRedirect.h.
    2) Compile the C file into a shared library, here's a makefile:
    StdoutRedirect: StdoutRedirect.o
    gcc -shared -o libStdoutRedirect.so StdoutRedirect.o
    3) Run the java class file.
    charlie
    **** StdoutRedirect.java ****
    import java.io.FileNotFoundException;
    import java.io.IOException;
    * This class, along with its JNI library, demonstrates a method of redirecting stdout of the JVM process to a Java
    * Reader thread. Using this method the stdout bytes can be sent anywhere in the Java program; e.g., displayed in a GUI.
    * This has only been tested on a Linux 2.6 kernel.
    public class StdoutRedirect {
        static {
            System.loadLibrary("StdoutRedirect");
        final static public String NAMED_PIPE = "/tmp/stdoutRedirect";
        native private void setupNamedPipe();
        native private void redirectStdout();
        native public void someRoutine();
        // Flag to indicate to Reader thread when to terminate
        protected boolean keepReading = true;
        public static void main(String[] args) throws IOException {
            StdoutRedirect redir = new StdoutRedirect();
            redir.setupNamedPipe();
            // The first reader or writer to connect to the named pipe will block. So, the reader
            // must be opened first and must be in a new thread. We want it to be in a separate
            // thread anyways so we can receive data asynchronously.
            redir.openReader();
            // At this point, the reader thread is blocked on creating the FileInputStream
            // because it is the first thing to connect to the named pipe. We grab the lock
            // here and redirect stdout to the named pipe. This opens a writer on the named
            // pipe and the reader thread will unblock. We want to wait for the reader thread
            // to unblock and be ready to receive data before continuing.
            synchronized (redir) {
                redir.redirectStdout();
                try {
                    // wait for the reader thread to be ready to receive data
                    redir.wait();
                } catch (InterruptedException e) {
            // write some data to stdout in our C routine
            redir.someRoutine();
            // All done now, so indicate this with our flag
            redir.keepReading = false;
            // The reader thread may be blocked waiting for something to read and not see
            // the flag. So, wake it up.
            System.out.println("Shut down");
            // Make sure everything is out of stdout and then close it.
            System.out.flush();
            System.out.close();
            // stdout is closed. This will not be visible.
            System.out.println("Won't see this.");
         * Starts the reader thread which listens to the named pipe and spits the data
         * it receives out to stderr.
        private void openReader() {
            new Thread() {
                public void run() {
                    try {
                        int BUFF_SIZE = 256;
                        byte[] bytes = new byte[BUFF_SIZE];
                        int numRead = 0;
                        // At this point there is no writer connected to the named pipe so this statement
                        // will block until there is.
                        FileInputStream fis = new FileInputStream(NAMED_PIPE);
                        // The reader thread is ready to accept data. Notify the main thread.
                        synchronized (StdoutRedirect.this) {
                            StdoutRedirect.this.notify();
                        // Keep reading data until EOF or we're told to quit and there is no more data to read
                        while (numRead != -1 && (StdoutRedirect.this.keepReading || fis.available() != 0)) {
                            numRead = fis.read(bytes, 0, BUFF_SIZE);
                            System.err.print("Received - " + new String(bytes, 0, numRead));
                        if (fis != null) {
                            fis.close();
                        System.err.println("Receiver shut down");
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
            }.start();
    } // class StdoutRedirect**** StdoutRedirect.c ****
    #include "StdoutRedirect.h"
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <stdio.h>
    #include <fcntl.h>
    #include <string.h>
    #include <errno.h>
    // The filesystem location for the named pipe
    const char *namedPipe = "/tmp/stdoutRedirect";
    * Create the named pipe we're going to redirect stdout through. After this
    * method completes, the pipe will exist but nothing will be connected to it.
    JNIEXPORT void JNICALL Java_StdoutRedirect_setupNamedPipe(JNIEnv *env, jobject obj) {
      // make sure there is no pre-existing file in our way
      remove(namedPipe);
      // create the named pipe for reading and writing
      mkfifo(namedPipe, S_IRWXU);
    * Redirect stdout to our named pipe. After this method completes, stdout
    * and the named pipe will be identical.
    JNIEXPORT void JNICALL Java_StdoutRedirect_redirectStdout(JNIEnv *env, jobject obj) {
      // Open the write end of the named pipe
      int  namedPipeFD = open(namedPipe, O_WRONLY);
      printf("Before redirection...\n");
      // make sure there is nothing left in stdout
      fflush(stdout);
      // duplicate stdout onto our named pipe
      if ( dup2(namedPipeFD, fileno(stdout)) == -1 ) {
        fprintf(stderr, "errno %s.\n", strerror(errno));
        fprintf(stderr, "Couldn't dup stdout\n");
      printf("After redirection.\n");
      // flushing is necessary, otherwise output does not stay in sync with Java layer
      fflush(stdout);
    * Do some random writing to stdout.
    JNIEXPORT void JNICALL Java_StdoutRedirect_someRoutine(JNIEnv *env, jobject obj) {
      int i;
      for ( i = 0; i < 3; i++ ) {
        printf("Message %d\n", i);
      printf("End of messages\n");
      // flushing is necessary, otherwise output does not stay in sync with Java layer
      fflush(stdout);
    }

  • Redirect output to jsh

    Hi there!
    I am working on a simple java shell in Windows XP at the moment which simply parses an entered command and passes it to ProcessBuilder as a list.
    It works ok - the process startsas expected - the only problem is I cannot see any output from the processes, nor can I figure out a way to redirect STDOUT to the running java shell from XP (which is what I really want).
    Here is my code so far - as I said, it's fairly basic at the moment.
    public class shell {
         public void start()throws java.io.IOException {
              String commandLine;
              BufferedReader console = new BufferedReader
              (new InputStreamReader(System.in));
              while(true)  {
                   System.out.print("jsh>");
                   commandLine = console.readLine();
                   if(commandLine.equals(""))
                        continue;
                   else process(commandLine);
                        continue;
         private void process(String cmd)
              String command = cmd;
              String[] commsplit = command.split("\\s");
              ProcessBuilder pb = new ProcessBuilder(Arrays.asList(commsplit));
              try {
              pb.start();
              catch (IOException ioe) {
                   System.err.println("Unknown command or input. Please try again");
         public static void main(String[] args)throws java.io.IOException {
              shell shell1 = new shell();
              shell1.start();
    }Any pointers in the right direction would be most appreciated.

    You need to process the stdout and stderr of the Process. This http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html shows you how to do it safely!

  • The stdout and stderr in javaw.exe enviroment

    hi,
    when i run a class using java.exe enviroment,the stdout and stderr is the console,but can someone tell me that where the stdout and stderr in javaw.exe is?
    or javaw.exe don't have stdout and stderr ?
    thanks for your answer

    When you use javaw.exe, whatever you send to stdout and stderr goes to what computer old-timers call the "Bit Bucket". That means it disappears. But you can redirect stdout to a file on your command line if you like.

Maybe you are looking for

  • Podcast episodes not updating correctly in iTunes

    Hello, I am having a problem with my podcast episodes not updating correctly in iTunes.  The last 5 episodes I published appeared in iTunes at the bottom of the episode list, as if they were old episodes--i.e., they appear as if they were the first 5

  • Problem moving folders with Lightroom 4.4 on Mac OS 10.7.5

    I am trying to move a folder of recently edited files from my desktop to an external drive where I keep all my processed files using Lightroom but I keep getting a message that the folder can not be moved. If I try to create a new folder on the exter

  • I HAVING PROBLEM IN THE PHOTO. THIS PROBLEM CAUSE ME TROUBLE IN PRESENTATION. PLS CHECK CASE NO 530618429

    I HAVING A PROBLEM ABOUT THE PHOTO APPS. THIS ISSUE CAUSE ME A LOT PROBLEM IN PRESENTATION, AND I DID CALL TO YOUR SERVICES CENTRE TO COMPLIANT ABOUT THIS ISSUE. PLS CHECK THE CASE NUMBER 530618429. I'M WAITING FOR THE NEW IOS UPDATE, BUT EVERYTIME U

  • Changes to the ESS Personal Data iview

    Hi There With regard to the 'Personal Data' iview on ESS. I have a scenario where fields marked as REQUIRED are DISABLED. How do i enable them ? When trying to change the field configuration by previewing the Personal Data iview and then doing 'contr

  • Please read this before posting?

    First of all we need your stats so we can determine if or not their is an issue:  Please use this link http://192.168.1.254 to go to your hubs homepage: (Heres the direct link! http://192.168.1.254/index.cgi?active_page=9116 )  Then click on Setting