编写程序实现以下功能:
1,在父进程中定义变量n,在子进程中对变量n进行++操作;并且打印变量n的值,打印子进程pid;
2,在父进程中打印变量n的值,并且打印父进程pid。
3,要求分别用fork和vfork创建子进程。
Vfork();
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
#include<sys/wait.h>
int main()
{
int n=0;
int pid = vfork();
if(pid == 0)
{
n++;
exit(0);
}
else if(pid > 0)
{
printf("n:%d\n",n);
}
else
{
printf("Error\n");
}
return 0;
}
fork()
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
#include<sys/wait.h>
int main()
{
int n=0;
int pid = fork();
if(pid ==0)
{
n++;
exit(0);
}
else if(pid > 0)
{
sleep(1);
printf("n:%d\n",n);
}
return 0;
}
知识点:
fork()与vfork()使用方法比较就这,没营养