Linux基础学习—exec与fork共同使用

33 篇文章 0 订阅
11 篇文章 0 订阅

exec与fork共同使用,修改配置文件数据

#include<sys/types.h>
#include<sys/stat.h>
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<fcntl.h>

int main()
{
	pid_t pid;
	while(1){
		int data;
		printf("input data,please.\n");
		scanf("%d\n",&data);

		if(data == 1){
			pid = fork();
			
			if(pid == 0){
				int fdSrc;
				char *readBuf = NULL;			
	
				fdSrc = open("conf.txt",O_RDWR);
	
				printf("%d\n",fdSrc);
				int size = lseek(fdSrc,0,SEEK_END);
				printf("%d\n",size);
				lseek(fdSrc,0,SEEK_SET);
				
				readBuf = (char *)malloc(sizeof(char)*size + 8);
				int n_read = read(fdSrc,readBuf,size);
				
				printf("%d\n",size);
				char *p = strstr(readBuf,"LENG=");
				if(p == NULL){
					printf("There is not that data\n");
					exit(-1);
				}

				p = p + strlen("LENG=");
				*p ='8';
				
				lseek(fdSrc,0,SEEK_SET);
				int n_write = write(fdSrc,readBuf,strlen(readBuf));
				
				close(fdSrc);
			}
		}
		else{
			printf("do nothing\n");
		}
	}
	return 0;

}

利用生成的可执行文件,用exec执行如下操作

#include<sys/types.h>
#include<sys/stat.h>
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<fcntl.h>

int main()
{
	pid_t pid;
	int data = 10;
	while(1){
		printf("input data,please.\n");
		scanf("%d",&data);

		if(data == 1){
			int fdSrc;
			pid = fork();
						
			if(pid > 0){
				wait(NULL);
					
			}
			if(pid == 0){
				execl("./fconf","fconf","conf.txt",NULL);	
			}
		}
		else{
			printf("do nothing\n");
		}
	}
	return 0;

}

配置文件
修改前:
PEED=3
LENG=5
SCORE=9
LEVEL=5

**修改后:**
	PEED=3
	LENG=8
	SCORE=9
	LEVEL=5

利用exec函数与fork函数简单操作修改配置文件。
学识浅薄,希望可以帮到您

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值