我需要关于这个示例应用程序的帮助。当我运行它的时候,它在子进程打印“子发送!”之后被卡住了。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#define INPUT 0
#define OUTPUT 1
int main()
{
int fd1[2];
int fd2[2];
int pid;
if (pipe(fd1) < 0)
exit(1);
if (pipe(fd2) < 0)
exit(1);
if ((pid = fork()) < 0)
{
perror("fork");
exit(1);
}
else if (pid == 0)
{
close(fd1[INPUT]);
close(fd2[OUTPUT]);
char *str = "Hello World!";
printf("Child sending!\n");
write(fd1[OUTPUT], str, strlen(str));
char *bufferc = (char *)malloc(1000);
char *readbufferc = (char *)malloc(80);
int rdc;
int gotdata = 0;
while (gotdata == 0)
while ((rdc = read(fd2[INPUT], readbufferc, sizeof(readbufferc))) > 0)
{
strncat(bufferc,readbufferc,rdc);
gotdata = 1;
}
printf("Child received: %s",bufferc);
free(readbufferc);
free(bufferc);
exit(0);
}
else
{
close(fd1[OUTPUT]);
close(fd2[INPUT]);
int rd;
char *buffer = (char *)malloc(1000);
char *readbuffer = (char *)malloc(80);
int gd = 0;
while (gd == 0)
while ((rd = read(fd1[INPUT],readbuffer, sizeof(readbuffer))) > 0)
{
strncat(buffer, readbuffer,rd);
gd = 1;
}
printf("Parent received: %s\n",buffer);
free(readbuffer);
printf("Parent sending!");
write(fd2[OUTPUT], buffer, strlen(buffer));
free(buffer);
}
return 0;
}另外,有没有一种方法可以在我使用fork时进行调试,因为gdb会自动转到父进程。
发布于 2009-11-01 06:07:12
子进程写入父进程后,它必须关闭管道的写入端,以便父进程知道它已到达EOF。
发布于 2009-10-31 22:56:33
有几件事是错误的:
fd2永远不会initialized.while ((rd =读取(fd1INPUT,读取缓冲区,大小为读取缓冲区))> 0) {strncat(缓冲区,读取缓冲区,rd);gd = 1;}
如果没有数据可读,read将阻塞并且不返回。唯一会使其退出的情况是,如果连接已关闭,并且子连接没有关闭它。
发布于 2009-10-31 22:57:58
你的代码中有很多bug。为什么在没有初始化的情况下使用fd2?去掉它。现在它停留在“子发送”上,因为管道读取是一个阻塞调用,而你把它放在一个永远不会返回的while循环中。请参阅管道的手册页。
如果您想要中断while循环,请关闭该管道所有写入端。
此外,要调试子进程,请在调试时调用follow-fork-mode ()之前使用gdb命令fork as子级。
https://stackoverflow.com/questions/1654550
复制相似问题