管道 day2作业

文章提供了三个C语言程序,它们利用管道(pipe)进行双向通信。第一个程序创建两个FIFO(有名管道),名为mypipe和yourpipe。第二个程序是父进程与子进程之间的通信,子进程从mypipe读取输入并写入yourpipe,父进程则从yourpipe读取并打印数据,直到接收到over信号。第三个程序与第二个类似,也是通过管道进行双向通信。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

利用管道,双向通信

#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>

int main(int argc,char *argv[])
{

    if(mkfifo("./mypipe",0664))
    {
     perror("wrong");
     return -1;
    }
    if(mkfifo("./yourpipe",0664))
    {
     perror("wrong");
     return -1;
    }

    getchar();

    system("./mypipe");
    system("./yourpipe");

return 0;
}

2.c

#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>

int main(int argc,char *argv[])
{


       pid_t vvv=fork();
    if(vvv<0)
    {
      perror("Wrong");
      exit(-1);
    }
    else if(vvv==0)
    {
    int myr=open("./mypipe",O_WRONLY);
    char buf[128];
    if(myr<0)
    {
      perror("Wrong");
      exit(-1);
    }
    while(1)
    {
     fgets(buf,sizeof(buf),stdin);
     buf[strlen(buf)-1]='\0';
     write(myr,buf,strlen(buf));
     if(strcmp(buf,"over"))
            break;
     }
    close(myr);
    exit(0);
     }

    else
    {
     int yourr=open("./yourpipe",O_RDONLY);
     char buf[128];
    
     if(yourr<0)
    {
      perror("Wrong"); 
      exit(-1);
    }
     while(1)
     {
      bzero(buf,sizeof(buf));
      read(yourr,buf,strlen(buf));

      if(strcmp(buf,"over")==0)
            break;
     printf("%s\n",buf);
     }
     close(yourr);
     wait(NULL);
     }


return 0;
}
 

3.c

int main(int argc,char *argv[])
{

    pid_t vvv=fork();
    if(vvv<0)
    {
      perror("Wrong");
      exit(-1);
    }
    else if(vvv=0)
    {
    char buf[128];
    int myr=open("./mypipe",O_WRONLY);
    if(myr<0)
    {
      perror("Wrong");
      exit(-1);
    }
    while(1)
    {
     fgets(buf,sizeof(buf),stdin);
     buf[strlen(buf)-1]='\0';
     write(myr,buf,strlen(buf));
     if(strcmp(buf,"over"))
            break;
     }
       close(myr);
    exit(0);
     }

    else
    {
        char buf[128];
        int yourr=open("./yourpipe",O_RDONLY);
    
     if(yourr<0)
    {
      perror("Wrong"); 
      exit(-1);
    }
     while(1)
     {
      bzero(buf,sizeof(buf));
      read(yourr,buf,strlen(buf));

      if(strcmp(buf,"over")==0)
            break;
     printf("%s\n",buf);
     }
     close(yourr);
     wait(NULL);
     }


return 0;
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值