生产者,消费者进程代码

#include "stdlib.h"

#include "string.h"

#include "stdio.h"

#include "wait.h"

#include "sys/types.h"

#include "sys/file.h"

#include "unistd.h"

char r_buf[4];  //读缓冲

char w_buf[4];  //写缓冲

int pipe_fd[2];

pid_t pid1, pid2, pid3, pid4;

int producer(int id);

int consumer(int id);

int main(int argc,char **argv)

{  

if(pipe(pipe_fd)<0)

{

        printf("pipe create error \n");

        exit(-1);

}

else

{

printf("pipe is created successfully!\n");

if((pid1=fork())==0)

      producer(1);

if((pid2=fork())==0)

      producer(2);

if((pid3=fork())==0)

      consumer(1);

if((pid4=fork())==0)

      consumer(2);

}

close(pipe_fd[0]);  //需要加上这两句

close(pipe_fd[1]);  //否这会有读者或者写者永远等待

    int i,pid,status;

for(i=0;i<4;i++)

 pid=wait(&status);  

   exit(0);

}

int producer(int id)

{

    printf("producer %d is running!\n",id);

    close(pipe_fd[0]);

    int i=0;

    for(i=1;i<10;i++)

    {

        sleep(3);

    if(id==1) //生产者1

             strcpy(w_buf,"aaa\0");

        else  //生产者2

             strcpy(w_buf,"bbb\0");

        if(write(pipe_fd[1],w_buf,4)==-1)

            printf("write to pipe error\n");

    }

    close(pipe_fd[1]);

    printf("producer %d is over!\n",id);

    exit(id);

}

int consumer(int id)

{

    close(pipe_fd[1]);

    printf("producer %d is running!\n",id);

    if (id==1)  //消费者1

strcpy(w_buf,"ccc\0");

    else  //消费者2

strcpy(w_buf,"ddd\0");

    while(1)

    {

         sleep(1);

     strcpy(r_buf,"eee\0");

     if(read(pipe_fd[0],r_buf,4)==0)

             break;   

         printf("consumer %d get %s, while the w_buf is %s\n",id,r_buf,w_buf);

    }

    close(pipe_fd[0]);

    printf("consumer %d is over!\n", id);

    exit(id);

}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值