编写程序实现以下功能:
1,在父进程中定义变量n,在子进程中对变量n进行++操作;并且打印变量n的值,打印子进程pid;
2,在父进程中打印变量n的值,并且打印父进程pid。
3,要求分别用fork和vfork创建子进程。
在进行程序编写之前,我们要明白vfork和fork的区别。
1.vfork产生的子进程和父进程共享代码段和数据段,而fork产生的子进程是拷贝父进程的数据段和代码段。
2.vfork产生的子进程的一定比父进程先运行,而fork产生的子进程和父进程的执行顺序不一定,由操作系统的调度决定。
3.vfork产生的子进程调用exit或exec族函数之后才能对父进程进行调度,如果在此之前子进程的运行依赖父进程的进一步执行结果,则会照成死锁。
程序结果分析:假设变量n的值为1,在vfork函数中,父进程打印的n值是2,而fork函数中的父进程打印的n值是1。
fork.c程序如下:
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int main()
{
int n = 1;
if(fork() == 0)
{
printf("This is child,the pid is%d\n",getpid());
printf("The n is: %d\n",++n);
}
else
{
printf("This is father,the pid is%d\n",getpid());
printf("The n is: %d\n",n);
}
return 0;
}
fork.c程序运行结果:
vfork.c程序如下:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
int n = 1;
pid_t pid;
pid = vfork();
if(pid < 0)
perror("vfork");
else if(pid == 0)
{
printf("This is child,the child's pid is: %d\n",getpid());
printf("The n is: %d\n",++n);
exit(0);
}
else
{
printf("This is father,the father's pid is: %d\n",getpid());
printf("The n is: %d\n",n);
}
return 0;
}
vfork.c程序运行结果:
通过两个程序的运行结果我们可以发现,之前的推理是正确的。
注意,在试验中的n的自加必须用++n。因为如果用n++,两个父进程输出的n值都会是1。
实验完成。