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);
}
以上代码实现的功能就是,我在父进程输入字符,你在子进程输出我输入的内容