1. 程式人生 > >c/c++ linux 程序間通訊系列3,使用socketpair,pipe

c/c++ linux 程序間通訊系列3,使用socketpair,pipe

linux 程序間通訊系列3,使用socketpair,pipe

1,使用socketpair,實現程序間通訊,是雙向的。

2,使用pipe,實現程序間通訊

使用pipe關鍵點:fd[0]只能用於接收,fd[1]只能用於傳送,是單向的。

3,使用pipe,用標準輸入往裡寫。

疑問:在程式碼2裡不寫wait函式的話,父程序不能結束,但是在程式碼3裡也沒有寫wait函式,父程序卻可以結束???

1,使用socketpair:

#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;
}

github原始碼

2,使用pipe:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <wait.h>

int main(){
  int p[2];
  pid_t pid;
  char buf[128];

  memset(buf, 0, sizeof(buf));

  if(pipe(p) != 0){
    perror("pipe");
    return 1;
  }

  pid = fork();
  if(pid < 0){
    perror("fork");
    return 1;
  }

  if(pid == 0){
    close(p[1]);
    read(p[0], buf, sizeof(buf));
    printf("child process : data form parent process [%s]\n", buf);
    exit(0);
  }
  else{
    close(p[0]);
    write(p[1], "aaaa", 4);
    printf("parent process : child process is %d\n", pid);
    int status;
    wait(&status);
  }
  return 0;
}

github原始碼

3,使用pipe,用標準輸入往裡寫。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <wait.h>

int main(){
  int p[2];
  pid_t pid;
  char buf[1024];

  memset(buf, 0, sizeof(buf));

  if(pipe(p) != 0){
    perror("pipe");
    return 1;
  }

  pid = fork();
  if(pid < 0){
    perror("fork");
    return 1;
  }
  if(pid == 0){
    printf("child process : my_id=%d\n",getpid());

    close(p[0]);
    //把標準輸出給管道1了
    dup2(p[1], fileno(stdout));

    char *argv[ ]={"ls", "/home/ys/cpp/network"};
    //利用ls命令,往標準輸出裡,輸入資料夾裡檔案的的名字,標準輸出又連線到了上面開的管道1裡。
    if(execve("/bin/ls", argv, NULL) < 0){
      perror("exec");
      return 1;
    }
    exit(0);
  }else{
    int n;
    FILE* filep;

    close(p[1]);
    printf("parent process : child process id=%d\n", pid);

    //先開啟管道1
    filep = fdopen(p[0], "r");
    if(filep == NULL){
      perror("fdopen");
      return 1;
    }

    //再從管道1裡讀取資料
    while(fgets(buf, sizeof(buf), filep) != NULL){
      printf("get:%s\n", buf);
    }
    int status;
    wait(&status);
  }
  return 0;
}

github原始碼

c/c++ 學習互助QQ群:877684253

本人微信:xiaoshitou5854