预览加载中,请您耐心等待几秒...
1/7
2/7
3/7
4/7
5/7
6/7
7/7

在线预览结束,喜欢就下载吧,查找使用更方便

如果您无法下载资料,请参考说明:

1、部分资料下载需要金币,请确保您的账户上有足够的金币

2、已购买过的文档,再次下载不重复扣费

3、资料包下载后请先用软件解压,在使用对应软件打开

写给linux编程的初学者,进程编程是linux编程首先要学习的东西,往后要学习进程之间通讯的一些编程。下面的是进程编程的一些基本函数。 1.用户标识(UID)和有效用户标识(EUID) 使用getuid函数和geteuid函数来获取当前进程的用户标识和有效用户标识 #include<stdio.h> #include<sys/types.h> #include<unistd.h> intmain(void){ printf("CurrentprocessUID:%ld\n",(long)getuid()); printf("CurrentporcessEUID:%ld\n",(long)geteuid()); return0; } 运行结果: CurrentprocessUID:500 CurrentprocessEUID:500 2.fork函数 通过fork函数并判断函数返回值,根据返回值来判断是在父进程还是子进程。 #include<stdio.h> #include<unistd.h> #include<sys/types.h> intmain(void){ pid_tpid; //fork函数如果返回值小于0,表示调用失败 //如果返回值为0,表示处于进程中,如果大于0,表示在父进程中 if((pid=fork())<0){ perror("Cannotcreatethenewprocess"); return1; }elseif(pid==0){ printf("Inthechildprocess!\n"); return0; }else{ printf("Intheparentprocess!\n"); return0; } } 运行结果: Inthechildprocesss!! Intheparentprocess!! 调用fork函数后,其后代码会被父子进程分别执行。 #include<stdio.h> #include<unistd.h> #include<sys/types.h> intmain(void){ fork(); printf("Willbeexecutedtwice\n"); return0; } 运行结果: Willbeexcutedtwice Willbeexcutedtwice 3.vfork函数 首先定义g_var为全局变量,var为局部变量,然后调用fork函数创建子进程,并在子进程对g_var变量和var变量进行修改。子进程在输出这两个变脸值后退出,输出父进程中的这两个变量的取值情况。 #include<stdio.h> #include<unistd.h> #include<sys/types.h> intg_var=0; intmain(void){ pid_tpid; intvar=1; printf("processid:%ld\n",(long)getpid()); printf("beforeexecutetheforksystemcall,g_var=%dvar=%d\n",g_var,var); if((pid=fork())<0){ perror("Cannotcreateanewprocess"); return1; }elseif(pid==0){ g_var++; var++; printf("processid:%ld,g_var=%dvar=%d\n",(long)getpid(),g_var,var); _exit(0); } printf("processid:%ld,g_var=%dvar=%d\n",(long)getpid(),g_var,var); return0; } 运行结果: Processid:24437 Beforeexcutetheforksystemcall,g_var=0var=1 Processid:24438,g_var=1var=2 Processid:24437,g_var=0var=1 修改上面的程序,将fork函数的语句进行替换,使用vfork函数,将代码保存并运行 #include<stdio.h> #include<unistd.h> #include<sys/types.h> intg_var=0; intmain(void){ pid_tpid; intvar=1; printf("processid:%ld\n",(long)getpid()); printf("beforeexecutetheforksystemcall,g_var=%dvar=%d\n",g_var,var); if((pid=vfork())<0){ perror("Cannotcreateanewprocess")