
1、实验目的
通过编写fork和exec等系统调用的程序,加深对系统进程及其控制的了解。
2、实验原理
后父子进程会同步运行,但父子进程的返回顺序是不确定的。设两个变量global和test来检测父子进程共享资源的情况。同时在进程退出时对exit和_exit的区别进行测试和说明;
exec函数族可以让启动一个外部程序。
3、实验内容
●1.编译执行,并分析结果:
执行结果:
the test content!
fork test!
global=24 test=2 Parent,my PID is 3236
global=23 test=1 Child,my PID is 3237
分析:
pid = fork(); 之后,pid == 0 的话,就是子进程,
子进程才执行:
global++;
test++;
所以输出:global=23 test=1 Child,my PID is 3237
主进程执行:
global+=2;
test+=2;
printf("global=%d test=%d Parent,my PID is %d\\n",global,test,getpid());
exit(0)
所以输出:global=24 test=2 Parent,my PID is 3236
●2.将上述代码最后的两行代码替换为注释掉替换为printf("global=%d test=%d Parent,my PID is %d",global,test,getpid());
重新编译,查看结果,解释原因。
输出:
the test content!
fork test!
global=23 test=1 Child,my PID is 3278
输出结果少了之前的第四行
原因:
exit()在结束调用它的进程之前,要进行如下步骤:
1.调用atexit()注册的函数(出口函数);按ATEXIT注册时相反的顺序调用所有由它注册的函数,这使得我们可以指定在程序终止时执行自己的清理动作.例如,保存程序状态信息于某个文件,解开对共享数据库上的锁等.
2.cleanup();关闭所有打开的流,这将导致写所有被缓冲的输出,删除用TMPFILE函数建立的所有临时文件.
3.最后调用_exit()函数终止进程。
_exit做3件事(man):
1,Any open file descriptors belonging to the process are closed
2,any children of the process are inherited by process 1, init
3,the process's parent is sent a SIGCHLD signal
●如果要改成execv,该怎样修改程序呢?
char *argv[] = {"ps
4、实验心得
●不知道exit()与_exit() 的区别在哪
解决方法:上网到搜索引擎找解答
●execv函数不知道怎么使用
解决方法:上网到搜索引擎找解答
收获:
互联网有无穷无尽的知识,我们要好好利用
