system函数
system函数:
Name:
System: execute a shell oommand------执行一个shell指令
#include <stdlib.h>
int system(const char *command);//参数是指针/字符串
System()函数的返回值如下:
成功,则返回进程的状态值;
当sh不能执行时,返回127;
失败返回-1;
system()函数功能强大,很多人用却对它的原理知之甚少
下面是linux版system函数的源码:
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <unistd.h>
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,NULL);//sh -c ./cmdstring====./cmdstring
-exit(127); //子进程正常执行则不会执行此语句
}else{
while(waitpid(pid, &status, 0) < 0){
if(errno != EINTER){
status = -1;
break;
}
}
}
return status;
}
system()函数调用/bin/sh来执行参数指定的命令,
/bin/sh 一般是一个软连接,指向某个具体的shell,
比如bash -c选项是告诉shell从字符串command中读取命令;
在该command执行期间,SIGCHLD是被阻塞的,
好比在说:hi,内核,这会不要给我送SIGCHLD信号,等我忙完再说;
在该command执行期间,SIGINT和SIGQUIT是被忽略的,意思是进程收到这两个信号后没有任何动作。
返回值:
如果system()函数调用/bin/sh时失败,返回127,
其它原因返回-1(fork失败父进程返回),
若参数string为空指针(null)则返回非0值,一般设为1,
如果调用成功则最后返回shell命令后的返回值(exit,return返回),
但是此返回值也可能是127,因此最后能再检查errno来确定执行成功
注:
在编写有SUID/SGID权限的程序时,请勿使用system(),会继承环境变量,通过环境变量会造成系统安全的问题
案例演示:
当父进程检测到输入为1的时候,创建子进程把配置文件的字段值改掉
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <sys/wait.h>
int main()
{
pid_t pid;
int data=10;
while(1)
{
printf("请输入数据:\n");
scanf("%d",&data);
if(data == 1)
{
pid=fork();
if(pid>0)
{
wait(NULL);//防止变成僵尸进程
}
if(pid==0)
{
//execl("./changdata","changdata","config.txt",NULL);//执行别的
system("./changdata config.txt",);//系统下执行的,可以直接敲打
exit(0);
}
}
else
{
printf("神码也不做\n");
}
}
return 0;
}
需要补充一个changdata 和config.txtSystem
System()可以代替exec,简单粗暴System(“ps”);
不一样之处:System()执行后返回源程序,继续后面的代码