进程间通信
每个进程各自有不同的用户地址空间,任何一个进程的全局变量在另一个进程中都看不到,所以进程之间要交换数据必须通过内核,在内核中开辟一块缓冲区,进程1把数据从用户空间拷到内核缓冲区,进程2再从内核缓冲区把数据读走内核提供的这种机制称为进程间通信(IPC,InterProcess Communication)。
进程间通信地方式
1,管道
管道分为有名和无名管道,以我目前地工作经验,管道使用地较少,用地最多地是在面试地时候,给面试官说进程间通信的方式有哪几种,其次就是在书上看到,因此这里仅作简单的介绍。
(1)管道是基于两个文件描述符进行通信,管道创建函数 原型 int pipe(int fd[2]),当一个管道创建时,会创建两个文件描述符,fd[0]固定读,fd[1]固定写,构成一个半双工通道,
(2)管道用于不同进程间通信,只能用于父子进程,通常先创建一个管道,然后fork()一个子进程,子进程会继承父进程的两个文件描述符,但父子进程只能一个留读,一个留写描述符。然后在父子进程里进行读写文件描述符就行了,
int pip_connect(){
pid_t pid;
int pipe_fd[2];
char buf[256],char data[255]={0};
int real_read,real_write;
memset(buf,0,sizeof(buf));
if(pipe(pipe_fd)<0)
{
printf("pipe create error!\n");
return -1;
}
if((pid = fork())==0)//child process
{
close(pipe_fd[1]);
sleep(5);
if((real_read = read(pipe_fd[0],buf,MAX_DATA_LEN)) > 0)
{
printf("%d bytes read form the pipe is:'%s'\n",real_read,buf);
}
close(pipe_fd[0]);
return 0;
}
else if(pid > 0)
{
sleep(2);
strcpy(data,"pipe connect!");
if((real_write = write(pipe_fd[1],data,strlen(data)))!=-1)
{
printf("parent wrote %d bytes :%s\n",real_write,data);
}
close(pipe_fd[1]);
waitpid(pid,NULL,0);
}
return 0;
}