在 C 中使用管道递增和转发整数
Increment and forward an integer using pipes in C
我正在尝试编写一个程序,在父进程中初始化一个整数,然后在第一个 fork() 中,我们将该值递增并将其沿着管道传递给当前子进程调用的下一个进程。这再进行 2 次。我的问题是我将整数初始化为 96,理想情况下,因为我们有 3 个进程,程序应该 return 99。但是,它 returns 'a',这意味着它只增加了一次.
这是我的代码:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
int main(int argc, char **argv)
{
int status;
int i;
int pipes[4];
pipe(pipes);
pipe(pipes + 2);
int num = 96;
if (fork() == 0)
{
dup2(pipes[1], 1);
close(pipes[0]);
close(pipes[1]);
close(pipes[2]);
close(pipes[3]);
num++;
write(pipes[1], &num, sizeof(int));
}
else
{
if (fork() == 0)
{
dup2(pipes[0], 0);
dup2(pipes[3], 1);
close(pipes[0]);
close(pipes[1]);
close(pipes[2]);
close(pipes[3]);
read(pipes[0], &num, sizeof(int));
num++;
write(pipes[3], &num, sizeof(int));
}
else
{
if (fork() == 0)
{
dup2(pipes[2], 0);
close(pipes[0]);
close(pipes[1]);
close(pipes[2]);
close(pipes[3]);
read(pipes[2], &num, sizeof(int));
num++;
write(1, &num, sizeof(int));
}
}
}
close(pipes[0]);
close(pipes[1]);
close(pipes[2]);
close(pipes[3]);
for (i = 0; i < 3; i++)
wait(&status);
}
- 如何打印整数?
- 为什么我的增量只工作一次?
你 close(pipe[0])
然后尝试从中读取。改为从 dup'd fd 读取。如果您检查从 read
和 write
返回的值,您会注意到此错误。
要打印整数,请使用 printf("%d", num)
而不是写入。 num
只增加一次的原因是最后的child中的read
失败了,并没有改变num
,所以read
后的num保留了它的值初始化时有。
您需要做的就是从条件内部删除 close
调用(所有管道在当前代码中关闭两次(或者,更准确地说,它们关闭一次然后一秒钟尝试关闭它们失败,但失败未被注意到))或 read/write from/to dup'd fd。
我正在尝试编写一个程序,在父进程中初始化一个整数,然后在第一个 fork() 中,我们将该值递增并将其沿着管道传递给当前子进程调用的下一个进程。这再进行 2 次。我的问题是我将整数初始化为 96,理想情况下,因为我们有 3 个进程,程序应该 return 99。但是,它 returns 'a',这意味着它只增加了一次. 这是我的代码:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
int main(int argc, char **argv)
{
int status;
int i;
int pipes[4];
pipe(pipes);
pipe(pipes + 2);
int num = 96;
if (fork() == 0)
{
dup2(pipes[1], 1);
close(pipes[0]);
close(pipes[1]);
close(pipes[2]);
close(pipes[3]);
num++;
write(pipes[1], &num, sizeof(int));
}
else
{
if (fork() == 0)
{
dup2(pipes[0], 0);
dup2(pipes[3], 1);
close(pipes[0]);
close(pipes[1]);
close(pipes[2]);
close(pipes[3]);
read(pipes[0], &num, sizeof(int));
num++;
write(pipes[3], &num, sizeof(int));
}
else
{
if (fork() == 0)
{
dup2(pipes[2], 0);
close(pipes[0]);
close(pipes[1]);
close(pipes[2]);
close(pipes[3]);
read(pipes[2], &num, sizeof(int));
num++;
write(1, &num, sizeof(int));
}
}
}
close(pipes[0]);
close(pipes[1]);
close(pipes[2]);
close(pipes[3]);
for (i = 0; i < 3; i++)
wait(&status);
}
- 如何打印整数?
- 为什么我的增量只工作一次?
你 close(pipe[0])
然后尝试从中读取。改为从 dup'd fd 读取。如果您检查从 read
和 write
返回的值,您会注意到此错误。
要打印整数,请使用 printf("%d", num)
而不是写入。 num
只增加一次的原因是最后的child中的read
失败了,并没有改变num
,所以read
后的num保留了它的值初始化时有。
您需要做的就是从条件内部删除 close
调用(所有管道在当前代码中关闭两次(或者,更准确地说,它们关闭一次然后一秒钟尝试关闭它们失败,但失败未被注意到))或 read/write from/to dup'd fd。