exec的功能:
在进程内部执行一可执行的文件,可以是二进制文件,也可以是shell脚本。
excel函数的作用:
函数原型:int execl(const char * path,const char * arg,…)
path:要执行的程序路径。可以是绝对路径或者是相对路径。
arg:程序的第0个参数,即程序名自身。相当于argv[O]。
返回值:excel函数调用成功,无返回值。调用失败,返回-1.
例程:
1 #include <sys/types.h>
2 #include <unistd.h>
3 #include <sys/stat.h>
4 #include <fcntl.h>
5 #include<stdlib.h>
6 #include<stdio.h>
7 #include<string.h>
8
9
10 int main()
11 {
12 pid_t repid;//定于repid 接受fork()函数的返回值
13 while(1)
14 {
15 int i;
16 printf("please input the data !\n");
17 scanf("%d",&i);
18 if(i==1)
19 {
20 repid=fork();
21 if(repid>0)
22 {
23 wait(NULL);
24 }
25 if(repid==0)
26 {
27 /*第一个参数表示文件路径,第二个参数表示要执行的文件
28 第三个参数,是作为参数传给changdata 的。规定excel函数
29 参数最后一个为空*/
30 execl("./changdata","changdata","config.txt",NULL);
31 perror("why of failed:");//如果execl调用失败,这句会打印错误信息
32 exit(0);
33 }
34 }else
35 {
36 printf("no thing \n");
37 }
38
39 }
40 return 0;
41 }
程序运行,等待我们输入一个值,当输入1,程序新建进程,子程序就会调用execl()函数,执行changdata.(changdata使我们事先编译好的文件)
程序运行结果:
CLC@Embed_Learn:~$ cat config.txt
LENG=9
CLC@Embed_Learn:~$ ./demo20.out
please input the data !
2
no thing
please input the data !
1
please input the data !
^C
CLC@Embed_Learn:~$ cat config.txt
LENG=5