system函数api的使用
#include <stdlib.h>
int system(const char *command);
返回值:
成功,则返回进程的状态值;不能执行时,返回127;失败返回-1;
分析源码:
#include
#include
#include
#include
int system(const char * cmdstring)
{
pid_t pid;
int status;
if(cmdstring == NULL){
return (1);
}
if((pid = fork())<0){
status = -1;
}
else if(pid == 0){
execl("/bin/sh", "sh", "-c", cmdstring, (char *)0);
-exit(127); //子进程正常执行则不会执行此语句
}
else{
while(waitpid(pid, &status, 0) < 0){
if(errno != EINTER){
status = -1;
break;
}
}
}
return status;
}
可以看出,system是建立子进程来运行execl(system是封装后的execl函数)
如果system()在调用/bin/sh时失败则返回127,其他失败原因返回