[英]I want to create two communication between parent and child residing in different C files using ordinary pipes (IPC)
I am trying to send message from parant.c to child.c and I am successfully receiving it in the child.c My question is that how can I send message back to the parent using second pipe from child.c I want the exact sequence of code. I am trying to send message from parant.c to child.c and I am successfully receiving it in the child.c My question is that how can I send message back to the parent using second pipe from child.c I want the exact sequence的代码。
Here is my parent.c:这是我的父母。c:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{
int fd[2];
char buf[] = "HELLO WORLD!", receive[100];
if (pipe(fd))
{
perror("pipe");
return -1;
}
switch (fork())
{
case -1:
perror("fork");
return -1;
case 0:
// child
close(fd[1]); // close write end
dup2(fd[0], STDIN_FILENO); // redirect stdin to read end
close(fd[0]); // close read end
execl("./child", NULL); // execute child
default:
// parent
close(fd[0]); // close read end
write(fd[1], buf, sizeof(buf)); // write to write end
close(fd[1]); // close write end
wait(NULL);
}
printf("\nEND~\n");
return 0;
}
I am sending buf ("Hello world") to the child by executing./child file.我通过执行./child 文件向孩子发送 buf(“Hello world”)。 Here is my child.c:这是我的孩子。c:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
int fd[2];
pid_t pid = fork();
char buf[100], child_msg[] = "From Child: Hello Parent";
if (pipe(fd))
{
perror("pipe");
return -1;
}
switch (pid)
{
case -1:
perror("fork");
return -1;
case 0:
read(STDIN_FILENO, buf, sizeof(buf));
printf("%s ", buf);
close(fd[1]);
default:
wait(NULL);
}
return 0;
}
I am receiving Hello world in this file.我在这个文件中收到 Hello world。 but now how can I send child_msg back to the parent?但现在我怎样才能将 child_msg 发送回父级? I don't how to do that.我不知道该怎么做。 I am stuck at this for last 14 hours.在过去的 14 个小时里,我一直被困在这上面。
From main pipe
:从main pipe
:
pipe() creates a pipe, a unidirectional data channel ...
So, you need 2 pipes, ie, you have to create 2 pipes in your main process that will also be inherited by the child process.因此,您需要 2 个管道,即您必须在主进程中创建 2 个管道,这些管道也将由子进程继承。
From your code, you are exec
ing another program, in such cases you might be better off with other IPCs and not pipe!从您的代码中,您正在exec
另一个程序,在这种情况下,您最好使用其他 IPC 而不是管道!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.