一、 实验目的
- 加深对进程概念的理解,明确进程和程序的区别。
- 进一步认识并发执行的实质。
- 分析进程争用资源的现象,学习解决进程互斥的方法。
二、 实验内容
- 运行程序,查看自己运行的结果,并进行分析。
- 编写程序,要求见附录部分
三、 代码及运行结果分析
程序一:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <error.h>
int main()
{
int i,j,k;
if (i=fork())
{
j=wait(NULL);
printf("Parent Process!\n");
printf("i=%d,j=%d,k=%d\n",i,j,k);
}
else
{
k=getpid();
printf("Child Process!\n");
printf("i=%d,j=%d,k=%d\n",i,j,k);
}
}
wait阻塞了父进程,所以先执行fork返回0,进入子进程板块,打印child process!此时i=j=fork()=0,k就是当前子进程的进程id。而后子进程退出,fork()返回子进程id,即i=fork()=95496,wait()不阻塞,j为父进程捕获子进程的id,也为95496,此时k为默认值0。
程序二:
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdlib.h>
#include <error.h>
int main()
{
int p1,p2;
while((p1=fork())==-1);
if(p1==0)
{
printf("b.My process ID is %d\n",getpid());
}
else
{
while((p2=fork())==-1);
if(p2==0){
printf("c.My process ID is %d\n",getpid());
}
else{
printf("a.My process ID is %d\n",getpid());
}
}
}
fork()调用后,产生父进程和子进程。子进程打印a.My process ID is……,父进程进入else语句块执行fork(),由此父进程再复制出一个子进程,父进程打印b.My process ID is……,子进程打印c.My process ID is……。
程序三:
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdlib.h>
#include <error.h>
void main()
{int m,n,k;
m=fork();
printf("PID:%d\t",getpid());
printf("The return value of fork():%d\t\t",m);
printf("he\n");
n=fork();
printf("PID:%d\t",getpid());
printf("The return value of fork():%d\t\t",n);
printf("ha\n");
k=fork();
printf("PID:%d\t",getpid());
printf("The return value of fork():%d\t\t",k);
printf("ho\n");
}
以he为结尾的是最开始fork()所产生的父子两个进程。一个id为96870,一个为96871,96871是96870的子进程,此时96871没有子进程,fork()返回的是0。以ha为结尾的是以上述两个进程为父进程,各自产生一个子进程。最后以ho为结尾的是以上述四个进程各自产生一个子进程所形成的。
程序四:
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdlib.h>
#include <error.h>
void main()
{
int p1,p2,i;
while((p1=fork())==-1);
if(p1==0){
for(i=0;i<50000;i++){
printf("son %d\n",i);}
}
else
{
while((p2=fork())==-1);
if(p2==0){
for(i=0;i<50000;i++){
printf("daughter %d\n",i);}
}
else{
for(i=0;i<50000;i++){
printf("parent %d\n",i);}
}
}
}
乱序执行
程序五:
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdlib.h>
#include <error.h>
void main()
{int m,n,k,j;
m=fork();
printf("PID:%d\t",getpid());
printf("The return value of fork():%d\t\t",m);
printf("he\n");
if(m>0){
k=fork();
printf("PID:%d\t",getpid());
printf("The return value of fork():%d\t\t",k);
printf("ha\n");
if(k>0){
j=fork();
printf("PID:%d\t",getpid());
printf("The return value of fork():%d\t\t",j);
printf("ho\n");
}
}
else{
n=fork();
printf("PID:%d\t",getpid());
printf("The return value of fork():%d\t\t",n);
printf("hi\n");
}}
通过条件判断对进程进行fork()函数的调用。
四、 实验心得
- 对linux操作系统有了进一步了解与熟悉
- 熟悉了虚拟机操作系统一些常用指令。
- 对进程的执行和fork函数有了更好的了解。