如果以fork()创建则会输出: [root@localhost linux]# ./fork child:i=11 parent:i=10 如果改为vfork(),则: child:i=11 parent:i=11
函数exec X()系列函数
用fork()函数创建紫禁城后,如果希望在当前子进程中运行新的程序,则可以调用execX系列函数。
注意:当进程调用exec函数后,该进程的用户空间资源完全有新程序代替。
这些函数的区别在于:
1、指示新程序的位置是路径还是文件名
2、在使用参数时是使用参数列表哈市使用argv[]数组
3、后缀有l(list)表示使用参数列表,v表示使用argv[]数组
具体如下所示:
#include<unistd.h> int execl(const char *pathname,const char *arg0,.../*(char *) 0 */); int execv(const char *pathname,char *const argv[]); int execle(const char *pathname,const char *arg0,.../*(char *) 0 ,char *const envp[] */); int execve(const char *pathname,char *const argv[],char *const envp[]); int execlp(const char *filename,const char*arg0,.../*(char *) 0*/); int execvp(const char *filename, char *const argv[]); int fexecve(int fd,char *const argv[],char *const evnp[]);
一个实例:
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
int main(int argc ,char* argv[]) {
pid_t pid;
if ((pid=fork())==-1)
printf("error");
else if (pid==0)
execl("/bin/ls","ls","-l",argv[1],(char *)0);
else
printf("father okn");
}
运行可以看到在子进程中执行了ls命令。
[yqtao@localhost linux]$ gcc -o exec execX.c [yqtao@localhost linux]$ ./exec /home father ok
//execlp()函数使用
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
int main(int argc ,char* argv[]) {
execlp("ls","ls","-l","/home",(char*)0);
}
//execv()函数的使用
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
int main(int argc ,char* argv[]) {
char* argv1[]={"ls","-l","/home",0};
execv("/bin/ls",argv1);
}
ecvp()会从环境变量PATH所指定的目录中查找文件名作为第一个参数,第二个及以后的参数由参数列表,注意最后一个成员必须为NULL
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
int main(int argc ,char* argv[]) {
char* argv1[]={"ls","-l","/home",0};
execvp("ls",argv1);
}
总结
以上就是本文关于深入解读Linux进程函数fork(),vfork(),execX()的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!








