Linux下system函数的源码:
#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的参数可以很明显看出来就是在终端的命令
当system接受的命令为NULL时直接返回
否则fork出一个子进程,父进程使用waitpid等待子进程结束(放置僵尸金进程),子进程则是调用execl来启动一个程序,
execl("/bin/sh", “sh”, “-c”, cmdstring,(char*)0)是调用shell,这个shell的路径是/bin/sh,后面的字符串都是参数,然后子进程就变成了一个 shell进程,这个shell的参数是cmdstring。
为了更好的理解system()函数返回值,需要了解其执行过程,实际上system()函数执行了三步操作:
1.fork一个子进程;
2.在子进程中调用exec函数去执行command;
3.在父进程中调用wait去等待子进程结束。
1) 对于fork失败,system()函数返回-1。
2)如果exec执行成功,也即command顺利执行完毕,则返回command通过exit或return返回的值。(注意,command顺利执行不代表执行成功,比如command:“rm debuglog.txt”,不管文件存不存在该command都顺利执行了)
3)如果exec执行失败,也即command没有顺利执行,比如被信号中断,或者command命令根本不存在,system()函数返回127. 如果command为NULL,则system()函数返回非0值,一般为1.
直接放两段代码品味品味吧:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(){
if(system("date") == -1){
printf("ERROR!\n");
perror("why");
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <wait.h>
int main(){
char temp;
pid_t pid;
while(1){
printf("Please input a data!\n");
scanf("%c",&temp);
getchar();
if(temp == '1'){
pid = fork();
if(pid == 0){
//====================================
system("./changeDate demo2");// |
//====================================
exit(0);
}else if(pid > 0){
wait(NULL);
//防止变成僵尸进程
}
}else{
printf("It seems that you are wrong!\n");
}
}
return 0;
}