码迷,mamicode.com
首页 > 系统相关 > 详细

多进程轮流输出1-100

时间:2020-04-21 10:10:17      阅读:89      评论:0      收藏:0      [点我收藏+]

标签:while   pes   end   space   name   ==   ++   code   int   

#include <unistd.h>
#include <cstdio>
#include <cstring>
#include <stdlib.h>
#include <iostream>
#include <sys/types.h>
#include <string.h>
#include <string>
using namespace std;
int fd1[2], fd2[2];
void fun1(){
    cout << "fun1\n";
    char buf[105];
    while(1){
        memset(buf, 0, sizeof(buf));
        if(read(fd1[0], buf, sizeof(buf)) != -1){
            int *a = (int *)buf;
            cout << "fun1 = " << *a << endl;
            int c = *a + 1;
            memset(buf, 0, sizeof(buf));
            memcpy(buf, &c, sizeof(int));
            write(fd2[1], buf, sizeof(int)); 
            if(c >= 100){  cout << "fun1 end\n";  return;}
        }
    }
}
void fun2(){
    cout << "fun2\n";
    char buf[105];
    while(1){
        memset(buf, 0, sizeof(buf));
        if(read(fd2[0], buf, sizeof(buf)) != -1){
            int *a = (int *)buf;
            if(*a > 100){ cout << "fun2 end\n";   return;}
            cout << "fun2 = " << *a << endl;
            int c = *a + 1;
            memset(buf, 0, sizeof(buf));
            memcpy(buf, &c, sizeof(int));
            write(fd1[1], buf, sizeof(int)); 
        }
    }
}
int main(){
    pipe(fd1), pipe(fd2);
    int a = 0;
    write(fd1[1], &a, sizeof(int));
    pid_t pid = fork();
    if(pid == 0){
        fun2();
    }else{
        fun1();
        wait(&pid);
    }
    return 0;
}

多进程轮流输出1-100

标签:while   pes   end   space   name   ==   ++   code   int   

原文地址:https://www.cnblogs.com/qq136155330/p/12742125.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!