How do I redirect printf to new Konsole window in C?

61 views Asked by At

I have program, which uses threads to run 2 functions separately. I want output of func1 be in console window from which I launch program and output of func2 to be in newly created window. Any suggested solutions on that?

I use system("konsole"); to create new console in func2, but it just freezes output in first window (I mean program is running, but output is frozen till I close new console window).

2

There are 2 answers

0
n. m. could be an AI On

This works for me (on Linux with /proc mounted by default; other operating systems, or Linux with /proc not mounted, won't work).

  #define KONSOLE_BUFSIZE 512
  char buf[KONSOLE_BUFSIZE];
  FILE* p = popen("konsole -e 'sh -c \"cat /proc/$PPID/fd/0\"'", "w");
  if (p == NULL ) { /* process error */ }
  setvbuf(p, buf, _IOLBF, KONSOLE_BUFSIZE);

  ...

  pclose(p);

Writes to p appear in the konsole window. We rely on the fact that the parent process of the shell is the terminal emulator itself, and steal its standard input.

A more POSIX-y way would be to set up a named pipe and have the program write to it, while cat in a spawned terminal emulator is reading from it.

0
Armali On

Small simplifications to n. m. could be an AI's fine answer:

    FILE *p = popen("konsole -e cat /proc/$$/fd/0", "w");
    …
    setlinebuf(p);

Besides, it may be worth noting that pclose causes cat and therewith konsole to terminate; if one rather wants to wait for the console window to be closed, wait(NULL) can be used before provided that no other child has been spawned.