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;
}
推荐阅读