您的位置:首页 > 运维架构 > Linux

第一课关于 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秒后退出。要求创建新进程后要进行出错

                 处理。

       

        解答:请看 第一课习题之我的解决方案。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  null 作业 linux path user