linux 进程通信种类及无名管道

linux进程之间通信有如下几种方式:

  • 无名管道
  • 有名管道
  • 消息队列
  • 信号
  • 信号量
  • 共享内存
  • socket
    无名管道类似于硬件中的串口,但是只能是半双工的方式而且只可以存在于子进程和父进程之间。
    两个函数:
pipe,pipe2  which used to create pipe 
int pipe(int pipefd[2]);
pipe2 has more flags in function
  • pipefd[0]:用于读管道
  • pipefd[1]:用于写管道
  • 成功后返回0;失败返回-1;

下面开始例程:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
void read_data(int *);
void write_data(int *);
int main (int argc,char *argv[])
{
    int pipes[2],rc;
    pid_t pid;
    rc=pipe(pipes);
    if(rc==-1)
    {
        perror("\npipes\n");
        exit(1);
    }
    pid =fork();
    if(pid==-1)
    {
        perror("fork error\n");
        exit(1);
    }
    else if(pid==0)
    {
        read_data(pipes);
    }
    else
    {
        write_data(pipes);
    }
    

}
void read_data(int pipes[])
{
    int c,rc;
    close(pipes[1]);//pipe looks like a file,so you can close is
    while((rc=read(pipes[0],&c,1))>0)
    {
        putchar(c);
    }
    exit(0);
}
void write_data(int pipes[])
{
    int c,rc;
    close(pipes[0]);//pipe looks like a file,so you can close is
    while((c=getchar())>0)
    {
        rc=write(pipes[1],&c,1);
        if(rc==-1)
        {
            perror("parent write error\n");
            close(pipes[1]);
            exit(1);
        }
        
    }
    close(pipes[1]);
    exit(0);
}

以上代码实现的功能就是,我在父进程输入字符,你在子进程输出我输入的内容

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

T触发器

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值