Actually, the best way to do that would be to use popen(), this executes a program and pipes the output back to you. It returns a FILE * from which you then can read the output of the program that you have run.
You see, exec and its siblings will completely replace the program that calls it with the program executed by exec...thus a call to exec will _never_ return.
What you normally do is to use fork() to create a copy of the process that is running your program, in this copy you then run exec on the program that is to be run by your program. This gives you a new process running the program that you wanted to run from your own.
If you want the output of that program you also would have to create a pipe that you connect to standard output for the newly created process and the other end goes back to your program. This way your program can read what the new process outputs. All this is done bt popen to save you the headache =)
thank you , can I do it not from the sortfile.txt , I want to sort sth from the main(), I mean the input data is in my main(), such as char * [] = { "hello","world","popen","rocks"}, because I have an application just like sort but it can only read data from stdin now , I donot want to read from the file because I have a so large data to be "sort" . Why I ask this question is I want to know how can I use the application from my process.
thank you very much , I think I cannot express how I want , I have an binary file (have not source ), it can read input from stdin and output to stdout, I want use it from my main(), so I must use exec . What I want is calling it from my main(), and my main() must get the output too.
Well, that's trickier, as far as I know popen only supports that you connect the file to either stdin or stdout, not both. So I guess you'd have to fork, pipe and exec yourself.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.