【发布时间】:2013-05-05 00:38:54
【问题描述】:
我正在尝试 fork 两个孩子。父级读取一行发送到管道。子 1 读取它并将其写入另一个管道,最后子 2 读取它。但是,输出始终是父获取行。谢谢!
#define MAX 80
void child();
void parent();
void childtwo();
char * getli();
void printline(char *buffer, int count);
char * convertCase(char *str);
int pipe1[2];
int pipe2[2];
int main(int argc, char **argv)
{
pipe(pipe1);
pipe(pipe2);
if(fork()){
if(fork()){
printf("1st\n");
parent();
exit(0);
}
else{
printf("3rd\n");
childtwo();
exit(0);
}
}
else{
printf("2nd\n");
child();
exit(0);
}
}
void child(){
char *buf;
int count = 0;
close(pipe1[1]);
close(pipe2[0]);
while(1){
buf = (char *) malloc(sizeof(char)*MAX);
read(pipe1[0], buf, MAX);
if (strcmp(buf,"quit")== 0){
printf("Child is leaving\n");
free(buf);
break;
}
else{
printf("Child: ");
printline(buf,strlen(buf));
write(pipe2[1],buf, strlen(buf)+1);
free(buf);
}
close(pipe2[1]);
close(pipe1[0]);
exit(0);
}
}
void childtwo()
{
char *buf;
int count = 0;
close(pipe2[1]);
buf = (char *) malloc(sizeof(char)*MAX);
while(1){
buf = (char *) malloc(sizeof(char)*MAX);
read(pipe2[0], buf, MAX);
if (strcmp(buf,"quit")== 0){
printf("Childtwo is leaving\n");
free(buf);
break;
}
else{
printf("Childtwo:");
printline(buf,strlen(buf));
free(buf);
}
}
close(pipe2[0]);
exit(0);
}
void parent(){
char * buffer;
int count = 0, done=0;
close(pipe1[0]);
while (done != 1){
printf("parent getting line: ");
buffer = getli();
write(pipe1[1],buffer, strlen(buffer)+1);
if (strcmp(buffer,"quit")== 0){
puts("parent goes away");
free(buffer);
break;
}
free(buffer);
}
close(pipe1[1]);
exit(0);
}
【问题讨论】:
-
您的子进程中存在内存泄漏,您在循环之前和循环内部分配了
bufboth。 -
感谢您的指出!但是删除它并没有解决问题
-
您是否检查过所有系统调用是否真正工作?您应该检查他们返回的内容,例如
read返回-1然后出现一些错误,您可以使用例如perror打印出错误。您应该为 所有 函数执行此操作,即使fork可能会失败。 -
一个问题是您的进程没有足够快地关闭足够的文件描述符。在执行任何其他操作之前,父进程应关闭管道 1 的读取端和管道 2 的两个描述符。第二个孩子应该先关闭管道 1 的描述符和管道 2 的写入端,然后再执行任何其他操作。中间进程需要关闭管道 1 的写入端和管道 2 的读取端。如果您正在复制描述符(到标准输入和输出),您将需要执行更多关闭操作。
-
你的程序不完整:
undefined reference to `printline'undefined reference to `getli'