k, I had to change my first example a bit...since your script is to stay on. I've made a little program that echos
Code:
#include <stdio.h>
int main(void)
{
char buffer[50];
while (1)
{
fgets(buffer, sizeof(buffer), stdin);
printf("%s", buffer);
fflush(stdout);
}
return 0;
}
which is run with the main program
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define BUFFSIZE 256
void pipe_error(int input, int output, const char *msg)
{
perror(msg);
close(input);
close(output);
exit(1);
}
void child_handler(int input_pipe[], int output_pipe[])
{
/* close unneeded */
close(input_pipe[1]);
close(output_pipe[0]);
/* change stdin, stdout */
dup2(input_pipe[0], 0);
dup2(output_pipe[1], 1);
close(input_pipe[0]);
close(output_pipe[1]);
execl("PATH TO ECHO GOES HERE", "myecho", (char *)0);
exit(0);
}
void parent(int input_pipe[], int output_pipe[])
{
int ret_val;
char buffer[BUFFSIZE], *ptr;
close(input_pipe[1]);
close(output_pipe[0]);
while (1)
{
bzero(buffer, BUFFSIZE);
printf("Enter line to echo\n>");
fgets(buffer, sizeof(buffer), stdin);
ret_val = write(output_pipe[1], &buffer, strlen(buffer));
if (ret_val <= 0)
pipe_error(input_pipe[0], output_pipe[1], "parent write");
ret_val = read(input_pipe[0], &buffer, sizeof(buffer));
if (ret_val <= 0)
pipe_error(input_pipe[0], output_pipe[1], "parent read");
printf("Got Back: %s\n", buffer);
}
close(input_pipe[0]);
close(output_pipe[1]);
exit(0);
}
int main(void)
{
int parent_to_child[2];
int child_to_parent[2];
int pid;
int ret_val;
ret_val = pipe(parent_to_child);
if (ret_val == -1)
{
perror("PIPE p2c");
exit(1);
}
ret_val = pipe(child_to_parent);
if (ret_val == -1)
{
perror("PIPE c2p");
exit(1);
}
pid = fork();
switch (pid)
{
case -1: perror("fork"); exit(1);
case 0: child_handler(parent_to_child, child_to_parent);
default: parent(child_to_parent, parent_to_child);
}
return 0;
}
works fine from what I can see...and is nearly exactly what your attempting
output:
Enter line to echo
>first line
Got Back: first line
Enter line to echo
>second line
Got Back: second line
Enter line to echo
>here's a third line
Got Back: here's a third line
Enter line to echo
>seems to be working
Got Back: seems to be working
Enter line to echo
>done testing
Got Back: done testing
Enter line to echo
>no way to exit
Got Back: no way to exit
Enter line to echo
>ctrl+c
Got Back: ctrl+c
Enter line to echo
>
this should help I hope