Linux函数system
与exec的区别
1、system()和exec()都可以执行进程外的命令,system是在原进程上开辟了一个新的进程,但是exec是用新进程(命令)覆盖了原有的进程。
2、system()和exec()都有能产生返回值,system的返回值并不影响原有进程,但是exec的返回值影响了原进程。
NAME
system - execute a shell command
SYNOPSIS
#include <stdlib.h>
int system(const char *command);
//返回值见下文
因为system在其实现中调用了fork、exec和waitpid,因此有3种返回值。
(1) fork失败或者waitpid返回除EINTR之外出错,则system返回-1,并且设置errno以指示错误类型。
(2) 如果exec失败(表示不能执行shell),则其返回值如同shell执行了exit(127)一样。
(3) 否则所以3个函数(fork、exec、和waitpid)都成功,那么system的返回值是shell的终止状态,其格式可以参考waitpid。
实例:
我们先演示通过下面代码(change.c)来更改文件(TEST.config)数据:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main(int argc,char *argv[])
{
int fdsrc;
char *readbuf = NULL;
if(argc != 2){
printf("param error\ni");
exit(-1);
}
fdsrc = open(argv[1],O_RDWR);
int size = lseek(fdsrc,0,SEEK_END);
lseek(fdsrc,0,SEEK_SET);
readbuf = (char *)malloc(sizeof(size)+8);
int n_read = read(fdsrc,readbuf,size);
char *p = strstr(readbuf,"LENG=");
if(p == NULL){
printf("not found\n");
exit(-1);
}
p=p+strlen("LENG=");
*p='5';
lseek(fdsrc,0,SEEK_SET);
int n_write = write(fdsrc,readbuf,strlen(readbuf));
close(fdsrc);
return 0;
}
编译运行结果如下:LENG已被改为5.
下面用system来对TEST.config进行更改:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/wait.h>
int main()
{
pid_t pid;
int data = 0;
while(1){
printf("please input a data\n");
scanf("%d",&data);
if(data==1){
pid=fork();
if(pid>0){
wait(NULL);
}
if(pid==0){
// execl("./change","change","TEST.config",NULL);
system("./change TEST.config");
}
}else{
printf("wait...\n");
}
}
return 0;
}
在system参数直接写为“./change TEST.config”
实例2:
简单一点来掩饰:
#include <stdlib.h>
#include <stdio.h>
int main()
{
printf("before system\n");
system("ps -l");
printf("after system\n");
return 0;
}
直接把system的参数改为“ps -l”。结果如下:
调用函数system,开辟新进程,运行完新进程后接着运行下面程序(printf(“atter system\n”))。