【发布时间】:2016-03-11 21:55:47
【问题描述】:
我正在拆分一个文件,通过pipe() 发送,让孩子找到他们指定的文件部分的总和,通过pipe() 将计算的总和返回给父母,让父母计算总和子总和。
我有一个工作程序。我的问题是它在收到显示正确的最终值后挂起。
我不确定我在做什么让父母期待更多信息,但我敢打赌这与我的 for() loop 包含我的孩子代码有关。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int numchild;
int i, j, len, fpos=0, val, count=0, total=0, alltotal=0;
pid_t pid;
int nums = 1000;
FILE * file;
printf("How many children to use: ");
scanf("%d", &numchild);
printf("\nWill use %d child process(es).\n", numchild);
int fd[2*numchild][2]; //parent+child pipe
// create all pipes
for (i=0; i<2*numchild; i++)
{
pipe(fd[i]);
}
for (i=0; i<numchild; i++)
{
if((pid = fork()) == 0) // child process
{
pid = getpid();
// read from parent
len = read(fd[i][0], &fpos, sizeof(fpos));
if (len > 0)
{
file = fopen("file1.dat", "r");
fseek (file, fpos, SEEK_SET);
count = 0;
total = 0;
printf("Child(%d): Recieved position: %d\n", pid, fpos);
// read from file starting at fpos
// add values read to a total value
while (count < (nums/numchild))
{
fscanf(file, "%i", &val);
total += val;
count++;
}
//write to parent
write(fd[i+numchild][1], &total, sizeof(total));
printf("Child(%d): Sent %d to parent.\n", pid, total);
}
else
{
printf("Child(%d): Error with len\n", pid);
}
_exit;
}
// parent process
pid = getpid();
fpos = ((i*nums*5)/numchild); // 5 is the offset of the file values
// write to child process
printf("Parent(%d): Sending file position to child\n", pid);
write(fd[i][1], &fpos, sizeof(fpos));
// wait for child responce
len = read(fd[i+numchild][0], &total, sizeof(total));
if (len > 0)
{
printf("Parent(%d): Recieved %d from child.\n", pid, total);
alltotal += total;
printf("Parent(%d): Total: %d\n", pid, alltotal);
}
else
{
printf("Parent(%d): Error with len\n", pid);
}
}
}
【问题讨论】:
-
您希望语句
_exit;做什么?你的编译器对这条线有什么看法? 你现在说什么,恶魔? -
@EOF 我认为它表明子进程已完成。这是不必要的吗?而且我的编译器没有给我消息,因为它不会产生错误。
-
您使用的是哪个编译器?你是如何调用编译器的?
_exit应该在哪里声明? -
@EOF 我只是在使用 gcc。我通过 linux 终端调用它。
-
您使用类似
_exit(0);的方式调用_exit。你只有_exit;,它获取_exit的地址,并且什么都不做。