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函数会用新的程序文本替代原来的程序文本运行
所以原文本的程序代码不会再运行