进程通信-无名管道PIPE

来源:互联网 发布:plsql怎么执行sql文件 编辑:程序博客网 时间:2024/05/16 05:33

进程间通信方式:

古老方式:
无名管道:PIPE
有名管道:FIFO  named pipe
信号:signal

系统IPC(进程间通信)
信号量(sem)
共享内存(shm)
消息队列(msg)

BSD:
套接字:socket


先说无名管道PIPE

PIPE:无名管道
原型:int pipe(int pipefd[2]);头文件为unistd.h
参数:两个文件描述符
说明:pipe()创建一个管道,一个单向数据通道,可用于进程间通信,pipefd用于返回两个文件描述符指管端.
         pipefd[0]指管道的读端,pipefd[1]指管道的写端.写入管道的写入端的数据被内核缓冲,直到从管道
         的读取端读取.
     适用于亲缘关系的进程中,随进程结束而结束,先申请管道,在创建进程,最后完成读写操作.
返回值:成功返回0,失败返回-1

测试代码:

#include<stdio.h>#include<string.h>#include<unistd.h>#include<stdlib.h>#include <fcntl.h> void main(){int pipefd[2];pid_t fd;char test[]="pipe test is runing";char reader[24]={0};if(pipe(pipefd)==-1){printf("create pipe error!\n");exit(0);}fd=fork();if(fd==-1){printf("fork error!\n");exit(0);}//getpid返回当前进程标识,getppid返回父进程的标识if(fd==0){printf("child process:getpid:%d,getppid:%d,pid:%d\n",getpid(),getppid(),fd);close(pipefd[0]);//关闭读  完成写write(pipefd[1],test,strlen(test));}else{printf("parent process:getpid:%d,getppid:%d,pid:%d\n",getpid(),getppid(),fd);close(pipefd[1]);read(pipefd[0],reader,strlen(test));printf("reader is:%s\n",reader);}return;}
测试结果:

[root@libmaster zxd]# ./a.out 
parent process:getpid:1206,getppid:601,pid:1207
child process:getpid:1207,getppid:1206,pid:0
reader is:pipe test is runing




原创粉丝点击