Transferring file contents through a bi-directional handset

I will start with a brief explanation of my program, then move on to my question. I created a bi-directional handset that does the following:

  • The parent process passes the string value to the child process (in my program, the string value is "TEST DATA")
  • The child process reads the transferred data from its parent and executes the python file, which simply concatenates the two lines together (the line obtained from the parent process "TEST DATA" with "CHILD PROCESS:")
  • The attached lines are sent back to the parent process, which simply prints them.

    • after running this program, the output will look like this:

parent process: CHILD PROCESS: TEST DATA

and these are my c ++ and python code codes:

test.cc:

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>
#include <cstdlib>

int main()
{
  int writepipe[2] = {-1,-1};// parent -> child
  int readpipe[2] = {-1,-1};//child -> parent
  pid_t childpid;

  if(pipe(readpipe) < 0 || pipe(writepipe) < 0)
    {
      //cannot create a pipe
      printf("error creating pipe");
      exit(-1);
    }
#define PARENT_READ readpipe[0]
#define CHILD_WRITE readpipe[1]
#define CHILD_READ writepipe[0]
#define PARENT_WRITE writepipe[1]

  if((childpid=fork())<0)
    {
      //cannot fork child
      printf("cannot fork child");
      exit(-1);
    }
  else if (childpid==0)
    {//child process
      close(PARENT_WRITE);
      close(PARENT_READ);
      dup2(CHILD_READ,0); //read data from pipe instead of stdin
      dup2(CHILD_WRITE , 1);//write data to pipe instead of stdout
      system("python test.py");
      close(CHILD_READ);
      close(CHILD_WRITE);
    }
  else
    {
      close(CHILD_READ);
      close(CHILD_WRITE);
      //do parent stuff
      write(PARENT_WRITE,"TEST DATA\n",23);
      int count;
      char buffer [40];
      count=read(PARENT_READ,buffer,40);
      printf("parent process: %s",buffer);
    }
  return 0;
}

test.py:

import sys
data=sys.stdin.readline()
sys.stdout.write("CHILD PROCESS: "+data)

My question is: I have a text file (let's call it test.txt) that contains several lines of data, and I want to be able to use the previous code, but instead of sending one string value (TEST DATA) I want to send the contents of the whole text file .. Any hints?

+4
source share
1 answer

C , , . , . gulp, . , , , ... , . - tdelaney

0

Source: https://habr.com/ru/post/1622378/


All Articles