linux 下进程学习(2)

fork 与 exec()函数簇

 

fork_exec.c

#include <unistd.h>
#include <stdio.h>

char * const msg[3]={"b.out","爸爸叫你",NULL};

int main()
{
    
    
    
    pid_t p;
    printf("father pid %d\n",(int)getpid() );
    p = fork();
    execv("./b.out",msg);
    
    
    
    
    
    if(p==0)
    {
        
    printf(" father pid %d\n",(int)getpid() );
    
    }
    
    if(p!=0)
    {
        
    printf(" son pid %d\n",(int)getpid() );
    
    }
    
    
}
    
  

 

 

fork_exec_son.c

 

#include <unistd.h>
#include <stdio.h>

int main(int argc,char **argv)
{
    printf(" i am son pid %d\n",(int)getpid() );
    printf(" i get %s\n",argv[1]);
    while(1)
    {
        
    }
    
}
    
    

 

结果:

gec@ubuntu:/mnt/hgfs/ubunutu share/进程测试函数$ gcc fork_exec.c 
gec@ubuntu:/mnt/hgfs/ubunutu share/进程测试函数$ ./a.out 
father pid 4573
 i am son pid 4573
 i get 爸爸叫你
 i am son pid 4574
 i get 爸爸叫你


。。。。。(while)循环

 

ps-ef

 

gec       4573  2649 48 19:39 pts/2    00:02:19 b.out 爸爸叫你
gec       4574  4573 48 19:39 pts/2    00:02:19 b.out 爸爸叫你
gec       4591  4166  0 19:44 pts/4    00:00:00 ps -ef

 

所以可知

exec函数簇可以复制一个程序文本来覆盖原来的代码执行

 

所以子进程与父进程都会输出同样的东西

区别只是PID不同而已
 

 

 

 

exec函数会用新的程序文本替代原来的程序文本运行

所以原文本的程序代码不会再运行

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值