LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   C function to execute a program and return the output of the program (https://www.linuxquestions.org/questions/programming-9/c-function-to-execute-a-program-and-return-the-output-of-the-program-217697/)

ryan.n 08-14-2004 09:15 PM

C function to execute a program and return the output of the program
 
Hello. I am making a program in C to display the song xmms is playing using xosd. The only problem I have is how to retrieve the current song. I figured the best way would be to execute
Code:

xmmsctrl title
What function can I use to execute a program in C and return the output? Please give the function name and header file.

Thank you for your time.

itsme86 08-14-2004 09:16 PM

'man popen'.

ryan.n 08-14-2004 09:48 PM

Code:

FILE *f=popen("xmmsctrl title","r");
char *ch;
puts(ch);
pclose(f);

this gives me a segmentation fault.

itsme86 08-14-2004 09:59 PM

And it should. You're referencing an unitialized pointer, the behavior of which is undefined. You're lucky your program didn't send an e-mail bomb to your employer about the use of company facilities.

Try this instead:
Code:

FILE *f = popen("xmmsctrl title", "r");
// Note: should really check if f == NULL here.
char buf[1024];
fgets(buf, sizeof(buf), f)
pclose(f);
printf("Now playing: %s", buf);


ryan.n 08-14-2004 10:11 PM

thanks


All times are GMT -5. The time now is 08:02 AM.