[英]How to send multiple strings from parent to child processes trough pipe?
我正在尝试通过创建具有 3 个子进程的父进程来编写 C 代码,其中父进程通过 pipe 发送文件的五行,所有 3 个子进程在屏幕上打印接收到的字符串。
我知道关于这个主题有几个问题,但我无法解决我的问题,在那里寻找解决方案。
我的问题是只有第一个孩子接收字符串,打印它们然后程序停止。
这是代码:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#define MAX_CHILDREN 3
int main( void )
{
pid_t pid;
int fd[2];
FILE *f;
int num_process;
for(num_process = 0; num_process < MAX_CHILDREN; num_process++)
{
if(pipe(fd) == -1)
{
perror( "pipe Failed" );
continue;
}
pid = fork();
if(pid < 0)
{
perror("fork failed");
exit(1);
}
if(pid == 0)
{ //child code
char buff[256];
printf("Child %i (pid= %i)\n", num_process, getpid());
close(fd[1]);
while(read( fd[0], buff, sizeof(buff))>0)
{
printf("Read child = %s\n", buff);
}
exit(0);
}
else{//parent
printf("Im parent %i\n",getpid());
close(fd[0]);
int i;
int str_len=256;
char str[str_len];
f=fopen("input.dat","r");
for(i=0;i<5;i++)
{
fgets(str,str_len,f);
write(fd[1], str,strlen(str));
printf("Parent send %s\n", str);
}
wait(NULL);
}
}
fclose(f);
return 0;
}
我得到的 output 看起来像这样:
Im parent 65090
Parent send apple
Parent send banana
Parent send cherry
Parent send cat
Parent send dog
Child 0 (pid= 65091)
Read child = apple
banana
cherry
cat
dog
为什么程序在第一个孩子之后停止?
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#define MAX_CHILDREN 3
int main(void)
{
pid_t pid;
int fd[2];
FILE *f;
int num_process;
for (num_process = 0; num_process < MAX_CHILDREN; num_process++)
{
if (pipe(fd) == -1)
{
perror("pipe Failed");
return 0;
}
pid = fork();
if (pid < 0)
{
perror("fork failed");
exit(1);
}
if (pid == 0)
{ //child code
sleep(1); // for a nice output
char buff[256];
printf("Child %i (pid= %i)\n", num_process, getpid());
close(fd[1]);
while (read(fd[0], buff, sizeof(buff)) > 0)
{
printf("Read child = %s\n", buff);
}
close(fd[0]); // neccessary
exit(0);
}
else{//parent
printf("Im parent %i\n", getpid());
close(fd[0]);
int i;
int str_len = 256;
char str[str_len];
f = fopen("input.dat", "r");
for (i = 0; i < 5; i++)
{
fgets(str, str_len, f);
close(fd[0]); // neccessary
write(fd[1], str, strlen(str));
printf("Parent send %s\n", str);
}
close(fd[1]); // neccessary
wait(NULL);
}
}
fclose(f);
return 0;
}
你忘了关闭 pipe 数组,我在其中写了评论:必要的。 这就是为什么你的程序看起来像停止了。 我希望这对你有所帮助。
Output:
Im parent 398270
Parent send apple
Parent send bananana
Parent send cherry
Parent send cat
Parent send dog
Child 0 (pid= 398271)
Read child = apple
bananana
cherry
cat
dog
Im parent 398270
Parent send apple
Parent send bananana
Parent send cherry
Parent send cat
Parent send dog
Child 1 (pid= 398482)
Read child = apple
bananana
cherry
cat
dog
Im parent 398270
Parent send apple
Parent send bananana
Parent send cherry
Parent send cat
Parent send dog
Child 2 (pid= 398484)
Read child = apple
bananana
cherry
cat
dog
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.