Which command to use to execute a program within C++ code [Linux]?
Greetings,
Am new to C++ and Linux. Am looking for a command that I use to execute 3 executable programs (exe/bin) in my source code, and this what i want to do:
1. Know if the process executed successfully (return value) 2. Know process ID 3. Kill a processI tried System(), but it doesn't return on error and no PID, also not safe. I had a quick look at fork()-exec() but is it possible not to have parent-child relation? Also, i looked into the man pages but i didn't understand :(
Please, advice me on which command I shall use.
开发者_Python百科Thank you in advance!
Have you looked at popen()? This might be the way to go. Try the man page.
system() does return the exit code of the child process the same way wait() does (or -1
on error, or 127
if it failed to spawn the shell process).
If you need to know the PID of the child and run it asynchronously, fork() followed by exec() is usually the way to go. Use popen() instead if you want to communicate with the child process through a pipe.
To alleviate the inherent parent/child relationship, you'll probably have to daemonize the child process.
By definition, you always have a parent-child relation when starting new programs (except when they replace your own program in the current process; you get that when calling execl
without fork
ing first). Functions likes system
and popen
internally also call fork
and one of the exec
variants.
Have a look at Fork and Exec tutorial from the University of Cambridge, it's pretty straight-forward and to the point. Also uses C++. Note that all the relevant calls (fork
, execl
, wait
) are C POSIX functions.
精彩评论