How to make processes alternating?

As for threads, I have mutex and conditionals so I could manipulate them easily. However, if I create two processes by `fork()`, how could I make them alternating? Or, is there any way to create a "critical section" for processes? I intended to make a program that prints "r" and "w" alternatively, here is the code. #include #include int pipe_1[2]; int flag = 0; void r(); void w(); int main() { pipe(pipe_1); if(fork()) r(); else w(); } void r() { int count = 0; while(1) { printf("%d \n", flag); if (count == 10) exit(0); if(flag == 0) { puts("r"); flag = 1; count++; while(flag == 1) ; } } } void w() { while(1) { if(flag == 1) { puts("w"); flag = 0; while(flag == 0) ; } } } The out put is only: 0 r Then it seems to enter a infinite loop. What's the problem? And what's the right way to make alternating processes? Thanks.
I trust that you re doing this as an exercise and do know that the OS will take care of blocking processes when the pipe is full or empty as necessary, yes?

以上就是How to make processes alternating?的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » CSS3 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏