Implementation Principle
Strace Tracking Results:
Clone (Child_stack=0, flags=clone_parent_settid| SIGCHLD, parent_tidptr=0x7fff936fc388) = 15661
wait4 (15661, [{wifexited (s) && wexitstatus (s) = 0}], 0, NULL ) = 15661
The actual process:
1. Parent process-Clone () a child process
2. The parent process-WAIT4 () subprocess exits (if the SIGCHLD processing is SIG_DFL, the blocking wait refers to the child process exiting; if it is sig_ign, then return 1 immediately)
3. Sub-process-execl (/bin/sh-c command)
return value
Returns the possible case of a value:
-1:system () execution failed, such as clone () failure, WAIT4 () failure (return at sig_ign-1)
>=0:system () execution succeeds, command execution succeeds or fails, wexitstatus () Gets the return code executed by the command
the right way to use
1. Processing SIGCHLD Signal
2. wifexited () and Wexitstatus ()
#include <errno.h> #include <string.h> #include <stdlib.h> #include <signal.h> #include < string> #include <iostream> int main (int argc, char* argv[]) {char cmd[] = ' su www-c ' kdir-p-M 755/data
/inst-123456 &>/dev/null ' ";
sighandler_t Old_sighandler = Signal (SIGCHLD, SIG_DFL);
int RV = System (CMD);
Signal (SIGCHLD, Old_sighandler);
if ( -1 = = RV) {std::cout << "error:" << strerror (errno) << Std::endl;
return-1;
} std::cout << "return value:" << rv << Std::endl; if (wifexited (RV)) {std::cout << "subprocess exited, exit code:" << wexitstatus (RV) << std
:: Endl; if (0 = wexitstatus (RV)) {//If command returning 0 means succeed Std::cout << "co
Mmand succeed "<< Std::endl;
else {if (127 = = Wexitstatus (rv)) { Std::cout << "command not Found" << Std::endl;
Return Wexitstatus (RV); else {std::cout << command failed: << strerror (Wexitstatus (RV))
<< Std::endl;
Return Wexitstatus (RV);
}} else {std::cout << "subprocess exit failed" << Std::endl;
return-1;
return 0;
}
Command Background execution
If you want the command to execute in the background, you can add "&" to the command, but the consequence of this is that as long as system () execution succeeds, the return value is 0, regardless of whether the command exists or if the command execution succeeds.
Popen
http://blog.csdn.net/duyiwuer2009/article/details/50688493