资源描述:
《进程编程基础》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、实验:Linux下进程编程在Redhat测试如下程序,写出每个程序的实际运行结果,并写成实验报告上交。/dev/scsi/liostO/busO/targetO/lunO:plp2p3p4USBnewdeviceconnectonbus1/1,assigneddevicenumber3/dev/scsi/hostO/busO/targetO/lunO:plp2p3p41.用户标识(UID)和有效用户标识(EUID)使用gemid函数和geteuid函数來获取当前进程的用八标识和有效用八标识#include<
2、stdio.h>#include#includeintmain(void){printf(nCurrentprocessUID:%ld,(long)getuid());printf(nCurrentporcessEUID:%ldn,(long)geteuid());return0;}运行结果:CurrentprocessUID:500CurrentprocessEUID:5002.fork函数通过fork函数并判断函数返回值,根据返回值来判断是在父进程
3、还是子进程。#include#include#includeintmain(void){pid_tpid;//fork函数如果返冋值小于0,表示调用失败〃如果返冋值为0,表示处于进程屮,如果人于0,表示在父进程中if((pid=fork())<0){perror(nCannotcreatethenewprocess11);return1;}elseif(pid==()){printf(HInthechildprocess!");return
4、0;Jelse{printf(MIntheparentprocess!M);return0;)1运行结果:Inthechildprocesss!!Intheparentprocess!!调用fork函数后,其后代码会被父子进程分别执行。#include#include#includeintmain(void){fork();printf(MWillbeexecutedtwiceM);return0;}运行结果:Willbeexcuted
5、twiceWillbeexcutedtwice1.vfork函数首先定义g_var为全局变量,var为局部变量,然后调用fork函数创建子进程,并在子进程对g_var变量和var变量进行修改。子进程在输出这两个变脸值后退出,输出父进程中的这两个变量的取值情况。#include#include#includeintg_var=0;intmain(void){pid_tpid;intvar=l;printf(nprocessid:%ld,(l
6、ong)getpid());printf(Hbeforeexecutetheforksystemcall,g_var=%dvar=%dM,g_var,var);if((pid=fork())<0){perror(°Cannotcreateanewprocess11);return1;}elseif(pid==0){g_var++;var++;printf(Hprocessid:%ld,g_var=%dvar=%d,(long)getpid(),g_var,var);_exit(0);}printf
7、(Mprocessid:%ld,g_var=%dvar=%d,(long)getpid(),g_var,var);return0;}运行结果:Processid:24437Beforeexcutetheforksystemcall,g_var=0var=lProcessid:2443&g_var=1var=2Processid:24437,g_var=0var=l修改上而的程序,将fork函数的语句进行替换,使用vfork函数,将代码保存并运行#include#include8、std.h>#includeintg_var=O;intmain(void){pid_tpid;intvar=l;printf(Hprocessid:%ldt(long)getpid());printf(Hbeforeexecutetheforksystemcall,g_var=%dvar=%dM,g_var,var);if((pid=vfork())<0){perror(uC