进程的建立
实验内容
创建两个进程,让子进程读取一个文件,父进程等待子进程读取 完文件后继续执行,实现进程协同工作。进程协同工作就是协调好两个进程,使之安排好先后次序并以此执行,可以用等待函数来实现这一点。当需要等待子进程运行结束 时,可在父进程中调用等待函数。
实验代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| #include<sys/unistd.h> #include<sys/wait.h> #include <unistd.h> #include<stdio.h> #include<stdlib.h> int main(){ pid_t fpid=fork(); int count=0; if(fpid<0){ printf("error"); } else if(fpid==0){ printf("子进程:我是子进程,id=%d,开始读取文件:\n",getpid()); FILE *fp=fopen("test1file.txt","r"); if(fp==NULL){ printf("未找到文件\n"); } else{ char text[2000]; while (fgets(text,2000,fp)!=NULL) { puts(text); } } printf("子进程:读取文件结束\n"); exit(1); } else{ printf("父进程:我是父进程id=%d ,我要等待子进程\n",getpid()); int ret = waitpid(0,NULL,0); printf("父进程:子进程 已经结束,ret=%d\n", ret); } return 0; }
|
程序简要分析
该程序主要使用了fork()函数创建了子进程,然后让子进程读取文件并输出文件内容,同时父进程等待子进程的执行,这里用到了waitpid()函数。等待子进程运行完成后,父进程继续运行。
主要函数:pid_t fork(void)
pid_t waitpid(pid_t pid,int * status,int options)