Linux进程间同步和通信1-管道

2018-06-20  本文已影响0人  AmberXiao

目录:
1. 半双工管道
2. 命名管道
3. 消息队列
4. 信号量
5. 信号
6. 共享内存


不同通信机制的流程:


image.png

1 半双工管道

1.1 特点

1.2 pipe()函数

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

1.3 pipe()例程

#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
  int ret=-1;
  int fd[2];
  pid_t pid;
  char string[]="hey,guy!";
  char readbuf[80];

  int *write_fd=&fd[1];
  int *read_fd=&fd[0];

  ret=pipe(fd);
  if(ret==-1)
  {
    printf("pipe error!\n");
    return -1;
  }

  pid=fork();
  if(pid==-1)
  {
     printf("fork error!\n");
     return -1;
  }
  if(pid==0)
  {
    close(*read_fd);
    ret=write(*write_fd,string,strlen(string));
    return 0;
  }
  else
  {
    close(*write_fd);
    ret=read(*read_fd,readbuf,sizeof(readbuf));
    printf("receive :%d, %s\n",ret,readbuf);
  }
  return 0;
}

运行结果:

receive:8,  hey,guy!
上一篇 下一篇

猜你喜欢

热点阅读