欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

exec族函数配合fork使用

程序员文章站 2024-03-19 18:48:34
...

exec族函数配合fork使用
1.
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/wait.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);
}
else if(pid == 0){

    char *readBuf;
    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 fund\n");
            exit(-1);
    }
    p=p+strlen("LENG=");
    *p = '5';

    lseek(fdSrc,0,SEEK_SET);
    //ssize_t write(int fd, const void *buf, size_t count);
    int n_write = write(fdSrc,readBuf,strlen(readBuf));

//ssize_t read(int fd, void *buf, size_t count)
close(fdSrc);
}

            } else {
                    printf("wait,do nothing\n");
            }

    }
    return 0;

}
2.
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/wait.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);
}
else if(pid == 0){
execl("./changeData",“changeData”,“config.txt”,NULL);
}

            } else {
                    printf("wait,do nothing\n");
            }
    
    }
    return 0;

}

相关标签: 多进程