NAME
system - execute a shell command
SYNOPSIS
#include <stdlib.h>
int system(const char *command);
//运行程序的方法
./a.out
sh -c ./a.out
//Linux中的system源码(可以理解为封装的execl函数)
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()函数的返回值如下:
成功,则返回进程的状态值;当sh不能执行时,返回127;失败返回-1。
system是封装好的excel函数,但两者有区别:
//echoarg.c
#include <stdio.h>
int main(int argc,char **argv)
{
int i = 0;
for(i = 0;i < argc;i++){
printf("argv[%d]:%s\n",i,argv[i]);
}
return 0;
}
//execl.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
printf("before execl\n");
if(execl("./echoarg","echoarg","abc",NULL) == -1)
{
printf("execl failed\n");
}
printf("after execl\n");
return 0;
}
//system.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
printf("before execl\n");
if(system("./echoarg abc") == -1)
{
printf("execl failed\n");
}
printf("after execl\n");
return 0;
}
通过对比可知:
system最终还会返回到原程序中,执行后面的代码;
execl不会返回到原程序中,因此不会执行后面的代码。