LINUX系统编程__进程__exec族函数配合fork使用

该程序通过fork创建子进程,当接收到输入1时,子进程会读取并修改名为congfig.txt的配置文件,将LENG的值更改为5。主要涉及的系统调用包括open、read、write、lseek和execl。
摘要由CSDN通过智能技术生成

将此改为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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值