问题描述
父子进程共享一个计数器,每次父进程或子进程可以给计数器加一。
简单实现
#include<iostream>
#include<unistd.h>
#include<stdio.h>
#include<sys/wait.h>
using namespace std;
struct Shared{
int count;
};
Shared shared;
int main(){
pid_t pid;
shared.count = 0;
if((pid = fork()) ==0){
for(int x=0;x<10;x++){
printf("Child change count = %d\n",shared.count++);
}
return 0;
}
for(int x=0;x<10;x++){
printf("Parent change count = %d\n",shared.count++);
}
waitpid(pid,NULL,0);
}
运行结果