linux 進程間通信,使用socketpair,pipe


管道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 );  
        }  
    }  
}  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM