簡體   English   中英

通過管道將圖像發送到C中的子進程

[英]Sending image through pipe to child process in C

我的程序需要做的是創建子進程,然后將其轉換為dipslay程序,然后通過管道將其發送到PNG圖片。 我想我已經接近了,但是我不知道如何通過管道發送圖像。

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>

int main(void)
{
    int     fd[2];
    pid_t   childpid;

    char    string[] = "";
    char    readbuffer[10000];
char    buf[10000];
FILE *fptr;

    pipe(fd);

    if((childpid = fork()) == -1)
    {
            perror("fork");
            exit(1);
    }

    if(childpid == 0)
    {
            //Child
            close(fd[1]);
    dup(fd[0]);
    execl("/usr/bin/display","display", (char *)0);
    read(fd[0], readbuffer, sizeof(readbuffer));
            exit(0);
    }
    else
    {
    //Parent
    close(fd[0]);
    dup2(fd[1],1);
    printf("Type name of the file:\n");
    scanf("%s",string);
    fptr = fopen(string, "r");
     while ( fgets(buf, sizeof(buf), fptr) != NULL) {
            write(fd[1], buf, strlen(buf));
            }

    fclose(fptr);

    }

    return(0);

首先,您需要關閉與標准輸入關聯的文件描述符。

close(0);

然后復制fd [0]。 它應該工作。 您無需在父進程中復制fd [1]。

我的程序:

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


int main()
{
  int pipe_fd[2];
  int c;
  FILE *file;


  pipe(pipe_fd);

  if(fork()==0)
    {
      //child
      close(pipe_fd[1]);
      close(0);
      dup(pipe_fd[0]);
      execl("/usr/bin/display","display", (char*)NULL);
      read(pipe_fd[0], &c, 1);
      exit(1);
    }
      // parent
      close(pipe_fd[0]);
      file=fopen("Lena2.pgm","r");
      if(file==NULL)
        printf("File error\n");
      while(!feof(file))
        {
          c=getc(file);
          write(pipe_fd[1], &c, 1);
        }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM