Hey guys. I have to make two c programs, parent.c and child.c. Basically the parent will fork a new process for every child it needs to make, create a pipe and connect the stdio input or output of the new process to the pipe (which is also connected to the parent) and call an exec function for child.c. I get that when you call exec the stdin and stdout are inherited from the process but I'm unsure how to actually get the parent process and the child.c to communicate through the pipe. I've looked around for examples of this but I cant find exactly what I'm looking for.
If you could just show me how to send a string (char []) from the parent to the the child.c process that would be great. I'm not sure exactly what I'm doing wrong (or right for that matter lol).
Code:
#define __EXTENSIONS__
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#define COMM_TERM "OUT"
#define COMM_CONT "OVER"
#define MAX_BUFFER_SIZE 128
int main(void)
{
int pipe_one[2];
int status;
int wait_ret;
char buffer[MAX_BUFFER_SIZE];
/* Create a pipe. */
if(pipe(pipe_one) == -1)
{
perror("ERROR");
exit(EXIT_FAILURE);
}
/* Create first child process. */
if(fork() == 0)
{
/* first child process */
printf("First child process with pid %d alive.\n", (int)getpid());
/* Close unused pipe */
close(pipe_one[1]);
/* Attach Child 1 stdin to Parent stdout */
dup2(pipe_one[0], 1);
/* Exectute Child program */
execlp("./child", "child" ,"-f", NULL);
}
close(pipe_one[0]);
write(pipe_one[1], "You Beauty!!!", 127);
return EXIT_SUCCESS;
}
-child.c
[code]
#define __EXTENSIONS__
#include <unistd.h>
#include <strings.h>
#include <stdlib.h>
#include <stdio.h>
int
main(int argc, char *argv[])
{
int launchChild, flags, childOnly, opt;
char *pipeName;
int pipeLen, pfind;
char buffer[128];
while(1)
{
read(buffer, 127, stdin);
if(strcmp(buffer, "EXIT") == 0)
{
close(0);
exit(EXIT_SUCCESS);
}
if(strcmp(buffer, "You Beauty!!!") == 0)
{
printf("%s\n", buffer);
}
}
exit(EXIT_SUCCESS);
}
[\code]
Thanks for any help