将此改为changeData,作用当输入1时子进程修改配置文件
配置文件congfig.txt,内容如下:
SPEED=3
LENG=9 //将此配置文件改为LENG=5
SCORE=9
LEVEL=5
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <string.h>
#include <stdlib.h>
int main()
{
pid_t pid;
int data = 10;
while(1){
printf("please input a data:\n");
scanf("%d",&data);
if(data==1){
int fdSrc; //定义一个文件描述符
pid = fork(); //创建子进程
if(pid>0){
wait(NULL); //回收子进程资源,防止僵尸进程
}
if(pid==0){
char *readBuf = NULL;
fdSrc = open("congfig.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); //注意关闭文件,防止损坏内容
}
}
}
return 0;
}
exec族函数配合fork使用的代码部分
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <string.h>
#include <stdlib.h>
int main()
{
pid_t pid;
int data = 10;
while(1){
printf("please input a data:\n");
scanf("%d",&data);
if(data==1){
int fdSrc;
pid = fork();
if(pid>0){
wait(NULL);
}
if(pid==0){
execl("./changeData","changeData","congfig.txt",NULL); //注意路径
exit(0);
}
}
else{
printf("wait,do nothing\n");
}
}
return 0;
}