編寫程序實現以下功能:
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()使用方法比較就這,沒營養