linux 进程间通信,使用socketpair,pipe

你猜 阅读:745 2020-10-22 16:34:03 评论:0
管道pipe是半双工的,pipe两次才能实现全双工,使得代码复杂。socketpair直接就可以实现全双工

socketpair对两个文件描述符中的任何一个都可读和可写,而pipe是一个读,一个写

 

1,使用socketpair,实现进程间通信,是双向的。

2,使用pipe,实现进程间通信

使用pipe关键点:fd[0]只能用于接收,fd[1]只能用于发送,是单向的。

3,使用pipe,用标准输入往里写。

 

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <unistd.h> 
#include <sys/socket.h> 
#include <wait.h> 
 
int main(){ 
  int sv[2]; 
  pid_t pid; 
  char buf[128]; 
 
  memset(buf, 0, sizeof(buf)); 
 
  if(socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0){ 
    perror("socketpair"); 
    return 1; 
  } 
 
  pid = fork(); 
  if(pid < 0){ 
    perror("fork"); 
    return 1; 
  } 
  if(pid == 0){ 
    close(sv[0]); 
    read(sv[1], buf, sizeof(buf)); 
    printf("child process : data from parant process [%s]\n", buf); 
    exit(0); 
  } 
  else { 
    int status; 
    close(sv[1]); 
    write(sv[0], "HELLO", 5); 
    printf("parent process : child process id %d\n", pid); 
    wait(&status); 
  } 
 
  return 0; 
}

使用pipe,做全双工

 

 

#include <stdlib.h>   
#include <stdio.h>   
   
int main ()   
{   
    int fd1[2],fd2[2];   
    pipe(fd1);   
    pipe(fd2);   
    if ( fork() ) {   
        /* Parent process: echo client */   
        int val = 0;   
        close( fd1[0] );   
        close(fd2[1]);   
        while ( 1 ) {   
            sleep( 1 );   
            ++val;   
            printf( "parent Sending data: %d\n", val );   
            write( fd1[1], &val, sizeof(val) );   
            read( fd2[0], &val, sizeof(val) );   
            printf( "parent Data received: %d\n", val );   
        }   
    }   
    else {   
        /* Child process: echo server */   
        int val ;   
        close( fd1[1] );   
        close(fd2[0]);   
        while ( 1 ) {   
            read( fd1[0], &val, sizeof(val) );   
            printf( "son Data received: %d\n", val );   
            ++val;   
            write( fd2[1], &val, sizeof(val) );   
            printf( "son send received: %d\n", val );   
        }   
    }   
}  

 

标签:C++
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号