linux多进程编程(一).pdf
《linux多进程编程(一).pdf》由会员分享,可在线阅读,更多相关《linux多进程编程(一).pdf(7页珍藏版)》请在淘文阁 - 分享文档赚钱的网站上搜索。
1、最近因为一个偶然的原因要在linux平台上做一个模拟实验,其中要涉及到多进程的编程,所以特此写一系列的博客来总结一下多进程的编程问题。这一系列文章只适合解linux,并且在Linux下使用C语言写过程序的人。首先进程的概念就多说,所有大凡上过操作系统课的人一定对那一堆堆的图示永生难忘。使用进程前,解一个简单的linux命令“ps”命令,它用来显示当前系统进程:ps效果:psef效果:psax效果:此外还有psl,nice,renice命令及参数,具体的使用用man查询就可以一.启动一个新进程:#inlcudesystem(char*)这个函数可以执行一个新的shell命令,只是启动的新进程将会
2、取代当前进程,也即如果system启动成功,则其之后的代码将会被运行。下面是一个system的例子:运行效果如图所示:二.exec系列函数#includechar*environintexecl(constchar*path,constchar*arg0,.,(char*)0)intexeclp(constchar*file,constchar*arg0,.,(char*)0)intexecle(constchar*path,constchar*arg0,.,(char*)0,char*constenvp)intexecv(constchar*path,char*constargv)intex
3、ecvp(constchar*file,char*constargv)intexecve(constchar*path,char*constargv,char*constenvp)exec系列函数的作用是替换进程的映像,并且其会接受当前进程的所有资源,包括已经打开的文件句柄等等。这一系列函数可以分为两大类,包括以l系列,其接受一个指令路径或者目录,以可变参数,或者一个环境变参数变,但所有参数均需以空指针结尾;第二个系列是v系列,与l系列类似,只是其将可变参数变以数组的形式传递给函数一个exec的示例:1234567891 01 1#i n c l u d e#i n c l u d e v o
4、 i d m a i n()i n t r e s u l t _ c o d e p r i n t f(R u n n i n g p s w i t h s y s t e m n )r e s u l t _ c o d e =s y s t e m(p s a x&)i f(r e s u l t _ c o d e =1 2 7)p r i n t f(c a n t s t a r t a s h e l l )i f(r e s u l t _ c o d e =1)p r i n t f(s t a r t e r r o r )e l s e p r i n t f(r u
5、 n n i n g s u c c e s s )1234567891 01 11 2#i n c l u d e#i n c l u d e#i n c l u d e v o i d m a i n()p r i n t f(e x e c s e r i e s f u n c t i o n s t e s t n )p r i n t f(e x e c v e n )c h a r *c o n s t p s _ a r g v =p s ,a x ,0 c h a r *c o n s t p s _ e n v p =P A T H=/b i n:/u s r/b i n
6、,T E R M=c o n s o l e ,0 e x e c v(/b i n/p s ,p s _ a r g v)?运行效果如图:输入输出重定向:因为exec执行后会保留之前进程的已打开文件句柄,利用这个特性,我们可以写一个小的程序,这种思想是你可以包装一个你根本就知道源代码,只知道功能的程序。比如下面这个upper.c将文件改为大写输出,useupper.c包装它,并为它提供一个文件名参数效果如图:1 3 p r i n t f(D o n e.n )1234567891 01 1#i n c l u d e#i n c l u d e#i n c l u d e i n t m
7、a i n()i n t c h w h i l e(c h =g e t c h a r()!=E O F)p u t c h a r(t o u p p e r(c h)e x i t(0)1234567891 01 11 21 31 41 51 61 71 81 92 02 12 22 32 4#i n c l u d e#i n c l u d e#i n c l u d e i n t m a i n(i n t a r g c,c h a r *a r g v )c h a r *f i l e n a m e i f(a r g c !=2)p e r r o r(a r g u
8、 m e n t s n u m b e r l e s s t h a n 2 n )e x i t(1)f i l e n a m e =a r g v 1 i f(!f r e o p e n(f i l e n a m e,r ,s t d i n)p e r r o r(f i l e r e o p e n f a i l e d n )e x i t(2)e x e c l(./u p p e r ,u p p e r ,0)p e r r o r(p r o g r a m f a i l e d n )e x i t(3)?三.复制进程映像,fork()接下来这个方法就是大名
9、鼎鼎的fork()函数,相信所有使用过,甚至看过linux系列书籍的人都知道这个函数。它会将当前进程分裂成两个完全一样,但是完全独立的进程。有些书上会说用它来创立新进程,但是我觉得用分裂来得贴切,就像生物学中无丝分裂一样,它生成的两个进程除资源和ID同外,其他都一样#include#includepid_tfork(void)错误时返回1;在父进程中返回子进程ID;子进程中返回0,可以依次来区分当前在哪个进程中.下面是一个使用fork打印父子进程的示例1234567891 01 11 21 31 41 51 61 71 81 92 02 12 22 32 42 5#i n c l u d e#
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- linux 进程 编程
限制150内