简体   繁体   中英

Read and write from/to piped stdin,stdout

I need to pass infromations between 2 different processes and i tried to use pipes in order to do that. Since i never used them i tried to start from basics. However it seems i am unable to read the info from the child process and to write them back.

I have the following code:

int main()
{
int in,out;

popen2("./Reader/reader",&in,&out);
int result = write(in, "hello", sizeof("hello"));
char out_arr[100];

result = read(out, out_arr, sizeof("Received"));
fprintf( stderr, "%s\n", out_arr);

return 0;
}

Where popen2 is as follows:

#define READ 0
#define WRITE 1

pid_t
popen2(const char *command, int *infp, int *outfp)
{
int p_stdin[2], p_stdout[2];
pid_t pid;

if (pipe(p_stdin) != 0 || pipe(p_stdout) != 0)
    return -1;

pid = fork();

if (pid < 0)
    return pid;
else if (pid == 0)
{

    close(p_stdin[WRITE]);
    dup2(p_stdin[READ], READ);
    close(p_stdout[READ]);
    dup2(p_stdout[WRITE], WRITE);

    execl("/bin/bash", "bash", "-c", command, NULL);
    perror("execl");

    exit(1);
}

if (infp == NULL)
    close(p_stdin[WRITE]);
    else
    {

    *infp = p_stdin[WRITE];
    }

if (outfp == NULL)
    close(p_stdout[READ]);
else

{

    *outfp = p_stdout[READ];
}

return pid;
}

That opens a child process. How can i read the "hello" i write to pipe in the main process from the child process? How can i write back to the main process?

At the moment this seems not to work:

int main()
{

std::string input;
while(std::cin>>input)
{
    std::cout<<"Received";
}

return 0;
}

SOLVED

I missed \n\r at the end of the sent char array in order to be red from the child process.

int main()
{
int in,out;

popen2("./Reader/reader",&in,&out);
int result = write(in, "hello\n\r", sizeof("hello\n\r"));
char out_arr[100];

result = read(out, out_arr, sizeof("Received"));
fprintf( stderr, "%s\n", out_arr);

return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM