【发布时间】:2017-03-30 16:17:22
【问题描述】:
当我在 C 中处理 pipe() 函数时,我有点困惑。我的目标是在子进程之间传输数据。我希望每个孩子都接受来自fd[0] 的意见并写信给fd[1]。我的代码在这里,但我无法获得任何结果。错误在哪里?我怎么能想象管道?
int main()
{
char *arr = malloc(sizeof(int));
int num;
int fd[2];
char *piping = malloc(10*sizeof(char));
char *word = malloc(10*sizeof(char));
while(1)
{
printf("enter the number of child: ");
fflush(stdout);
fgets(arr, 10, stdin);
printf("enter word: ");
fflush(stdout);
fgets(word, 10, stdin);
num = atoi(arr);
pipe(fd);
for(int i = 0; i < num; i++)
{
if(!fork())
{
read(0, piping, 10);
if(i != 0)
{
dup2(fd[0],0);
}
if(i != num-1)
{
dup2(fd[1],1);
}
write(1, piping, 10);
}
else
wait(0);
}
}
return 0;
}
【问题讨论】:
-
为什么要动态分配?我看不出有什么需要,在你不需要的地方,你应该避免它。
-
另外,考虑使用
scanf()或sscanf()从用户输入中读取数字。 -
@JohnBollinger 也许你是对的,但这并不重要。这只是一个例子,我试图了解它是如何工作的以及如何实现它。所以,我只是写了任何数字。
-
此外,
dup2()呼叫对您的作用很小。他们让我对你实际想要达到的目标有点怀疑(如果我猜对了,那么你的做法是错误的),但你的代码实际上做了什么——以及你说它应该做什么-- 无需复制任何文件描述符即可。
标签: c pipe fork stdin file-descriptor