第一课关于 fork 和 exec 函数的学习
2009-09-18 15:21
465 查看
1. 函数原型:pid_t fork(void)
功能:完整地拷贝父进程的整个地址空间。
课本例子:
/*fork.c*/ #include <sys/types.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> int main(void) { pid_t result; result = fork(); if(result == -1){ perror("fork"); exit; } else if(result == 0){ printf("The return value is %d/nIn child process!!/nMy PID is %d/n",result,getpid()); } else{ printf("The return value is %d/nIn father process!!/nMy PID is %d/n",result,getpid()); } }
该程序 使用fork 函数新建了一个子进程,其中父进程返回子进程的PID,而子进程返回值为0;
注意点:
1.程序执行的时候,执行 fork 之后 父进程的 result 返回值应该为 子进程的PID,子进程返回0,可以用返回值判断当前是哪个进程。
2.子进程是复制了父进程的所有内容,除了PID,因此在父进程中的变量改变了,子进程中并不会有改变。例子如下:
#include <sys/types.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> int main(void) { pid_t result; int i = 9; result = fork(); if(result == -1){ perror("fork"); exit; } i++; printf("The value is %d/n", i); }
结果可想而知输出结果:
The value is 10
The value is 10
3. 和 vfork 不同的是,vfork 函数通过允许父子进程可访问相同物理内存,当子进程需要改变内存中数据时才拷贝父进程 (写操作时拷贝)
2. 函数原型:int execl(const char, const char *arg,....)
int execv(const char, char * const arg[],....)
...........
功能:进程执行另个程序调用的函数
例子:
#include <sys/types.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys/wait.h> int main(void) { pid_t result; result = fork(); if (result == -1) { perror("child1 fork"); exit(1); } else if (result == 0) { char *arg[]={"env", NULL}; char *envp[] = {"PATH=/tmp", "USER=sunq", NULL}; execvp("env", envp); //查找env 命令 并执行 它 传入参数 为 envp //execve("env", arg, envp); //查找env 命令 并执行 它 传入参数 为 arg, 执行环境设置 envp //execv("env", arg); //查找env 命令 并执行 它 传入参数 为 arg printf("return %d/n in child process!!/n this pid is %d/n", result,getpid()); } else { printf("return %d/n in Father process!!/n this pid is %d/n", result,getpid()); } }
注意点:
1. exec 函数族 不能直接执行管道命令,那么如何使用exec 执行管道命令呢?
课后作业:
1.创建3个进程,其中一个为父进程,其余两个是该父进程创建的子进程,其中一个进程运行一条Linux指令(该指令 要带管道命
令 如 : ls -l | more),该条指令自定;另一个子进程在打印一条提示信息并暂停3秒后退出。要求创建新进程后要进行出错
处理。
解答:请看 第一课习题之我的解决方案。
相关文章推荐
- 【操作系统】fork()、exec()函数学习笔记
- 计算机系统的初步学习(持续更新)--关于replace_byte()函数
- 关于fork()函数以及一个关于fork的笔试题
- 关于c#构造函数执行顺序的一些学习内容
- 守护进程学习————两次fork细节、deamon()函数
- c++函数学习-关于c++函数的林林总总
- 关于多进程编程中fork()函数返回两次的探究
- 关于非阻塞IO函数的学习
- 关于fork()函数的精辟分析
- sql cast,convert,QUOTENAME,exec 函数学习记录
- fork()和vfork()的区别,signal函数用法,exec()系列函数的用法小结
- Linux下的多进程编程(转) - fork(),exec()等函数的使用[zz]
- 关于SQLServer2005的学习笔记——分析函数
- Jquery中淡入淡出效果fadeIn()、fadeOut()、fadeToggle()、fadeTo()学习引发的思考----关于Jquery函数传参数
- 关于函数调用约定的学习笔记
- 关于fork,exec,waitpid以及fgets换行替换为null的说明
- linux 下的fork,exec 等函数的一个例子
- 关于 RegExp exec()方法的学习
- linux 下fork函数和exec 函数的区别
- 关于菜鸟学习memset()函数