【发布时间】:2018-06-19 13:09:43
【问题描述】:
我需要编写一个包含 2 个进程的程序,其中一个写入偶数,另一个写入奇数。结果,我必须有从 1 到 100 的数字。
我输入了这段代码,但是当涉及到进程部分时,它卡在了printProc() 函数中。我猜问题在于管道中的读写。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int fd[2];
int printProc(int startNumber, int procNumber);
int main()
{
pid_t childpid;
pipe(fd);
int start = 0;
write(fd[0], &start, sizeof(start));
if ((childpid = fork()) == -1)
{
perror("fork");
}
if (childpid == 0)
{
printf("run child\n");
printProc(1, 0);
}
else
{
printf("run parent\n");
printProc(2, 1);
}
return 0;
}
int printProc(int startNumber, int procNumber)
{
FILE *f;
f = fopen("output.txt", "a+");
int num = startNumber;
int proc;
while (num <= 100)
{
read(fd[1], &proc, sizeof(proc));
if (proc == procNumber)
{
fprintf(f, "%d", num);
num = num + 2;
proc = (proc + 1) % 2;
write(fd[0], &proc, sizeof(proc));
}
}
return 0;
}
【问题讨论】:
-
为什么是全球性的?为什么要打开文件?为什么忽略返回值?
pipe()的手册给出了一个示例代码,几乎可以满足您的需求……您在使用函数之前阅读了手册吗? -
@Nicholas Goncharov 整个简介用英文写会好很多。:)