进程间通信的基本概念
通过管道进行进程间通信
为了完成进程间通信,需要创建管道。管道并非属于进程的资源,而是和套接字一样,属于操作系统(也就不是fork函数的复制对象)。两个进程通过操作系统提供的内存空间进行通信。
//pipe1.c
#include <stdio.h>
#include <unistd.h>
#define BUF_SIZE 30
int main(int argc, char *argv[])
{
int fds[2];
char str[]="Who are you?";
char buf[BUF_SIZE];
pid_t pid;
pipe(fds);
pid=fork(); //调用fork函数复制的是用于管道I/O的文件描述符,而非管道
if(pid==0)
{
write(fds[1], str, sizeof(str));
}
else
{
read(fds[0], buf, BUF_SIZE);
puts(buf);
}
return 0;
}
通过管道进行进程间双向通信
#include <stdio.h>
#include <unistd.h>
#define BUF_SIZE 30
int main(int argc, char *argv[])
{
int fds[2];
char str1[]="Who are you?";
char str2[]="Thank you for your message";
char buf[BUF_SIZE];
pid_t pid;
pipe(fds);
pid=fork();
if(pid==0)
{
write(fds[1], str1, sizeof(str1));
//sleep(2);
read(fds[0], buf, BUF_SIZE);
printf("Child proc output: %s \n", buf);
}
else
{
read(fds[0], buf, BUF_SIZE);
printf("Parent proc output: %s \n", buf);
write(fds[1], str2, sizeof(str2));
//sleep(3);
}
return 0;
}
上面的代码运行后,会发现父进程在无期限等待。原因是向管道传递数据时,先读的进程会把数据取走。子进程读回自己向管道发送的数据,父进程调用read函数后将无期限等待数据进入管道。
为了进行双向通信,需要创建两个管道,各自负责不同的数据流动:
#include <stdio.h>
#include <unistd.h>
#define BUF_SIZE 30
int main(int argc, char *argv[])
{
int fds1[2], fds2[2];
char str1[]="Who are you?";
char str2[]="Thank you for your message";
char buf[BUF_SIZE];
pid_t pid;
pipe(fds1), pipe(fds2);
pid=fork();
if(pid==0)
{
write(fds1[1], str1, sizeof(str1));
read(fds2[0], buf, BUF_SIZE);
printf("Child proc output: %s \n", buf);
}
else
{
read(fds1[0], buf, BUF_SIZE);
printf("Parent proc output: %s \n", buf);
write(fds2[1], str2, sizeof(str2));
sleep(3);
}
return 0;
}