***简述:***在exec程序的进程中创建子进程调用changeData程序来进行修改a.config这个配置文件中的LENG。
首先我们先来看看changeData的代码
#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("pararm error\n");
exit(-1);
}
fdSrc=open(argv[1],O_RDWR);
int size=lseek(fdSrc,0,SEEK_END);
lseek(fdSrc,0,SEEK_SET);
readBuf=(char*)malloc(sizeof(char)*size+32);
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));
printf("change sucess!\n");
close(fdSrc);
return 0;
}
原理就是先用strstr()函数找到SPEED这个字符串,然后指针位移,修改目标字符,要注意调用write前要用lseek(fdSrc,0,SEEK_SET);
重新定位光标。
然后我们来看exec这个程序
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
int main()
{
pid_t pid;
int data =10;
while(1){
printf("please input a data\n");
scanf("%d",&data);
if(data == 1){
pid= fork();
if(pid ==0 ){
execl("./changeData","changeData","a.config",NULL);
exit(0);
}
}
else{
printf("do nothing\n");
}
}
return 0;
}
当我们输入1时,创建子进程,调用execl函数来执行changeData,我们来看看执行前后的结果。
当我们输入5,6等不满足条件的字符,不执行changeData,输入1,可以看到a.config中的LENG=8变成了LENG=5。
以上就是关于Linux下实现在exec配合fork在一定条件下修改配置文件原理,尚有不足之处,请各位大师指正。
salute CLC