C使用管道传输数据以使用共享内存写入文件

时间:2016-10-21 20:28:53

标签: c pipe shared-memory race-condition

我正在尝试在C中使用管道。我有两个在父进程和子进程之间创建两个管道。我必须读取一个4096字节的文件(如果有更少的话,则更小),我必须通过管道读取的数据量和读数的次数。例如,复制一个6KB 父文件将父文件的第一个4KB数据写入共享内存,并通过管道向子进程发送两个整数1和4096。子进程接收这两个数字,从共享内存复制4096个字节到输出文件,并通过另一个管道将1发送回父进程。收到1后, 父级将左侧2KB数据复制到共享内存,并将2和2048发送给子级。子进程从管道接收它们,将2048个字节复制到输出文件,并用2回复父进程。父母然后向孩子发送0,0。孩子收到0并回复0然后退出。父母 收到0并退出。

#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#define SIZE 4096
#define NUM_OF_PIPES 2
#define P_READ 0
#define P_WRITE 1
#define C_READ 2
#define C_WRITE 3

int main(int argv, char *argc[]) {


  /*Check if program is called correctly*/
  if(argv != 3) {
    printf("Please call program appropriately\n");
    exit(EXIT_FAILURE);
  }

  FILE *r, *w, *check;
  void *sharedMem;
  int pipes[4];
  int shm;
  char userInput[5];
  char *name = "dm11ad_cop4610";
  int inChild = 0;
  int inParent = 0;
  r = fopen(argc[1], "rb");
  check = fopen(argc[2], "rb");

  /*Check if read file can open*/
  if(r == NULL)  {
    perror("Error opening read file");
    exit(EXIT_FAILURE);
  }
  /*Check if write file can open*/
  if(check == NULL) {
    perror("Error with write file");
    exit(EXIT_FAILURE);
  }
  else {
    fseek(check, 0, SEEK_END);
    int writeLen = ftell(check);
    if(writeLen > 0) {
      rewind(check);
      printf("Would you like to overwrite file (yes/no): ");
      scanf("%s", userInput);
      if(!strcmp(userInput, "yes")) {
        printf("Overwriting file...\n");
        w = fopen(argc[2], "wb");
      }
      else if(!strcmp(userInput, "no")) {
        printf("Will not overwrite\n");
        exit(EXIT_FAILURE);
      }
      else {
        printf("User input not accepted\n");
        exit(EXIT_FAILURE);
      }
    }
  }

  for (int i = 0; i < NUM_OF_PIPES; i++) {
    if (pipe(pipes+(i*2)) < 0) {
        perror("Pipe");
        exit(EXIT_FAILURE);
    }
  }

  /*Check if forking process is successful*/
  pid_t pid = fork();
  if(pid < 0) {
    perror("Fork");
    exit(EXIT_FAILURE);
  }

  shm = shm_open(name, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
  if(shm == -1) {
    perror("Shared memory");
    exit(EXIT_FAILURE);
  }
  if(ftruncate(shm, SIZE) == -1) {
    perror("Shared Memory");
    exit(EXIT_FAILURE);
  }

  sharedMem = mmap(NULL, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm, 0);
  if(sharedMem == MAP_FAILED) {
    perror("Mapping shared memory");
    exit(EXIT_FAILURE);
  }

  if(pid == 0) {
    while(inParent); 
    inChild = 1; 
    printf("I am in child\n");
    close(pipes[P_READ]);
    close(pipes[P_WRITE]);
    printf("Closed P pipes\n");
    int cBytes, len;
    printf("Im stuck\n");
    len = read(pipes[C_READ], &cBytes, sizeof(cBytes));
    printf("There are %i bytes\n", len);
    if(len < 0) {
      perror("Failed to read from pipe");
      exit(EXIT_FAILURE);
    }
    else if(len == 0) {
      printf("End of fle reached\n");
    }
    else {
        printf("Writing to file\n");
        fwrite(sharedMem, 1, sizeof(sharedMem), w);
      }

    printf("Closing C pipes\n");
    close(pipes[C_READ]);
    close(pipes[C_WRITE]);
    printf("Exiting Child\n");
    inChild = 0;
  }
  else {
  while(inChild);
  inParent = 1;
  close(pipes[C_READ]);
  close(pipes[C_WRITE]);
  int pBytes;

  int P2SHM = fread(sharedMem, 1, SIZE, r);
  if(P2SHM < 0) {
    perror("Could not store to shared memory");
    exit(EXIT_FAILURE);
  }

  if(write(pipes[P_WRITE], &P2SHM, sizeof(int)) < 0) {
    perror("Failed to write to pipe");
    exit(EXIT_FAILURE);
  }

  int C2P = read(pipes[P_READ], &pBytes, sizeof(int));
  if(C2P < 0) {
    perror("Failed to read value from pipe");
    exit(EXIT_FAILURE);
  }
  else if(C2P == 0) {
    printf("End of file reached\n");
  }
  else {
    printf("Received succesfully\n");
  }

  close(pipes[P_READ]);
  close(pipes[P_WRITE]);
  inParent = 0;
  printf("Waiting for child\n");
  wait(NULL);
  }
  return 0;
}

printfs可以帮助我查看程序在执行期间的位置。它在儿童过程中陷入困境,似乎在

期间
 len = read(pipes[C_READ], &cBytes, sizeof(cBytes));

这是一项作业,所以请不要将代码作为答案发布,而是请让我理解我做错了什么。感谢

2 个答案:

答案 0 :(得分:1)

孩子和父母之间的同步机制看起来很可疑:

while(inParent); 
inChild = 1; 

while(inChild);
inParent = 1;

inChildinParent的初始值为0。创建子进程后,每个进程都拥有自己的变量值副本。当您更改inChild = 1inParent = 1时,它仅在当前流程中更改。其他过程没有看到新值,也无法等待输入/输出。

要修复它,您应该使用更好的同步算法,例如处理信号量。阅读"5.2 Processes Semaphores"以获取详细信息。

答案 1 :(得分:1)

  

它在儿童过程中陷入困境,似乎在

期间
len = read(pipes[C_READ], &cBytes, sizeof(cBytes));

是的,我想是的。

我认为,在为管道端文件描述符设置单个4元素数组时,你有点太聪明了。这本身并不是错误的,但它往往会掩盖一些事情。

考虑管道应该为您做什么:一个进程写入管道的写入端,另一个进程读取从同一个管道的读取端写入的内容。仔细查看每个进程正在读取和写入的文件描述符。