Ubuntu下Linux进程间通信——匿名管道

Ubuntu下Linux进程间通信——匿名管道

Linux进程间通信——匿名管道

Linux进程间通信——FIFO(有名管道)

Linux进程间通信——消息队列

Linux进程间通信——信号量

Linux进程间通信——共享内存

Linux提供了多种进程间通信的方法,常见有管道(匿名)、FIFO(有名管道)、消息队列、信号量、共享内存,socket通信
1.匿名管道
匿名管道是最古老的进程间通信方法,两个进程间管道传递数据是单向的。

#include <unistd.h>
int pipe(int filedes[2]);

filedes会返回两个文件描述符,filedes[0]为读端,filedes[1]为写端。创建成功pipe()会返回0,失败返回-1。
实例

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

int main()
{
    int fd[2];
    int fd1[2];
    pid_t pid;
    char buf[64]="I am parent process!\n";
    char line[64];
    //创建管道
    if(0!=pipe(fd))
    {
        fprintf(stderr,"Fail to create pipe!\n");
        return 0;
    }
    //创建进程
    pid=fork();
    if(pid<0)
    {
        fprintf(stderr,"Fail to create process!\n");
        return 0;
    }
    //父进程
    else if(0<pid)
    {
        close(fd[0]);
        write(fd[1],buf,strlen(buf));
        close(fd[1]);
    }
    //子进程
    else
    {
        close(fd[1]);
        read(fd[0],line,64);
        printf("DATA From Parent :%s\n",line);
        close(fd[0]);
    }

    return 0;
}

匿名管道通信只能单向通信。父进程向子进程写数据。同一时刻,父进程只能向子进程写入数据,或者读出数据。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值