exec配合fork使用:
实现功能,当父进程检测到输入为1的时候,创建子进程把配置文件的字段值修改掉
1、输入1,建立一个子进程,修改config.txt中的内容
SPEED=5
LENG=9
SCORE=9
LEVEL=7
代码实现:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.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){
int fdsrc;
char *readbuf=NULL;
fdsrc=open("config.txt",O_RDWR);
int size=lseek(fdsrc,0,SEEK_END);
lseek(fdsrc,0,SEEK_SET);
readbuf=(char *)malloc(sizeof(char)*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);
}
}
else{
printf("wait,do nothing\n");
}
}
return 0;
}
编译运行结果:
SPEED=5
LENG=5
SCORE=9
LEVEL=7
可以看出,LENG=9变为了LENG=5
2、使用exec实现
gcc demo13.c -o changedata:生成changedata
cp ../file_biancheng/changedata .:将file_biancheng文件夹里的changedata拷贝到当前文件夹
代码实现:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.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){
wait(NULL);
}
if(pid==0){
execl("./changedata","changedata","config.txt",NULL);
exit(0);
}
}
else{
printf("wait,do nothing\n");
}
}
return 0;
}
编译运行:输入1后的结果:同样将LENG值修改成了5
SPEED=5
LENG=5
SCORE=9
LEVEL=7
节约了代码量