[英]Using Fork() and Pipe() to sum a file split to multiple child processes
[英]Using multiple processes to read a file and sending numbers through pipe()
我必须使用fork(2)
来制作用户输入的尽可能多的子代。
然后,我需要他们分解工作,读取坐标点的txt文件,将它们之间的距离与输入的距离进行比较。
然后,他们将它们的计数加到给定距离内。 每个孩子都必须将其计数写入管道,而父级必须读取每个计数并将其添加到总数中,然后将其打印出来。 这是我的代码:
int main( int argc, char *argv[] ) {
int distance = atoi(argv[1]);
if ( argc != 3 || sscanf( argv[ 1 ], "%d", &distance ) != 1 )
fail( "usage: pairs <distance>" );
readPoints();
int workers = atoi(argv[2]);
// Compute the square of the distance bound, since that's what we'll
// need to compare against.
int dsq = distance * distance;
// Count up the number of nearby pairs of points.
int total = 0;
int fd[2]; // pipe
if ( pipe( fd ) != 0 ){
fail( "Can't create pipe" );
}
int pid; // child
int chNum; // child's number
int c;
for( chNum = 0; chNum < workers; chNum++){
c = 0;
pid = fork();
if ( pid == -1 ){ //failure
fail( "Can't create child process" );
}
if( pid ==0 ){ // it's a child
for ( int i =chNum; i < ptCount; i+=workers)
for ( int j = i + 1; j < ptCount; j++ ) {
// Check the squared distance.
int dx = ptList[ i ].x - ptList[ j ].x;
int dy = ptList[ i ].y - ptList[ j ].y;
if ( dx * dx + dy * dy <= dsq )
c++;
}
close(fd[READ]);
lockf(fd[WRITE], F_LOCK,0);
write(fd[WRITE], &c, sizeof(c));
lockf(fd[WRITE], F_ULOCK,0);
close(fd[WRITE]);
exit(0);
}
else if(pid>0){ // this is parent
int d;
close(fd[WRITE]);
read(fd[READ], &d, sizeof(d));
close(fd[READ]);
total = total + d;
}
}
if(pid>0){
wait(NULL);
printf( "Total: %d\n", total );
}
return 0;
}
我使用for循环使fork(2)
,然后让他们计算计数并将其发送到要由父级读取的管道。 父级读入d
并将其加到total
。 我想知道我是否在正确使用管道将每个孩子的计数发送给父母,和/或我是否在正确地分叉,因此它仅来自一个父母。 当我使用一个以上的孩子时,我得到了错误的总数。
如果我使用1个孩子,则总结果为166428,这是正确的,但是例如,当我使用4个孩子时,它的总值为164908。有人可以帮助我吗?
您没有正确处理管道。
首先,您不需要锁定/解锁即可写入管道或从管道读取数据:小于PIPE_BUF
字节的写入保证是原子的。 POSIX.1-2001要求PIPE_BUF
至少为512个字节; 因为您一次只写sizeof(int)
个字节,所以很安全(除非sizeof(int)
大于或等于512,这是无稽之谈)。 见man limits.h
,在路径名变量值 :
{PIPE_BUF}
写入管道时保证是原子的最大字节数。 最低可接受值:{_ POSIX_PIPE_BUF}
这本身就简化了代码,并减少了不必要的锁定/解锁开销。
但是真正的问题在这里:
else if (pid > 0) { // this is parent
int d;
close(fd[WRITE]);
read(fd[READ], &d, sizeof(d));
close(fd[READ]);
total = total + d;
}
您无法在循环内关闭fd[WRITE]
:在派生下一个进程时,请考虑下一次迭代中会发生什么。 下一个循环中的子进程将尝试写入已经关闭的文件描述符,因此会发生错误(并且EBADF
导致write(2)
失败,但是您从不检查write(2)
的返回值,因此代码愉快地忽略该错误)。 另外,您尝试一次又一次关闭fd[WRITE]
,因此close(2)
也会返回错误(再次忽略该错误)。
对于read(2)
同样:如果关闭fd[READ]
,则在下一次迭代中无法从管道中读取结果; read(2)
将返回错误,并且close(2)
也将返回。
(因此,经验教训是:不要忽略错误。如果您正确地进行了错误处理,那么您将有很清楚的线索来了解发生了什么问题)
您不需要关闭。 子进程将确切的workers
整数写入管道。 父进程从管道中精确地读取workers
整数,所以这就足够了:
for (chNum = 0; chNum < workers; chNum++) {
c = 0;
pid = fork();
if (pid == -1)
fail("Can't create child process");
if (pid == 0) { // it's a child
for (int i = chNum; i < ptCount; i += workers) {
for (int j = i + 1; j < ptCount; j++) {
// Check the squared distance.
int dx = ptList[i].x - ptList[j].x;
int dy = ptList[i].y - ptList[j].y;
if (dx*dx + dy*dy <= dsq) {
c++;
}
}
}
ssize_t written = write(fd[WRITE], &c, sizeof(c));
if (written == -1)
perror("write error");
if (written != sizeof(c))
fail("Write failed on pipe");
exit(0);
}
else {
int d;
if (read(fd[READ], &d, sizeof(d)) != sizeof(d))
fail("Read error on pipe");
total += d;
}
}
关键是要了解,只要计划派生将使用管道的新进程,就需要保持fd[READ]
和fd[WRITE]
打开。
现在,这解决了问题,但是您对并行性有一种错误的感觉:如果没有可用数据,默认情况下,管道中的读取将阻塞。 这意味着在每次迭代中,父级直到相应的子级写入管道之前都不会取得进展。 因此,您并没有真正并行化任何东西。 其效果与让父项分叉,等待子项终止,读取结果并将其添加到总计,然后分叉下一个子项(并重复循环)相同。
如果您想要真正的并行性,则必须派生每个进程,然后才开始从管道读取。 像这样:
for (chNum = 0; chNum < workers; chNum++) {
c = 0;
pid = fork();
if (pid == -1)
fail("Can't create child process");
if (pid == 0) { // it's a child
for (int i = chNum; i < ptCount; i += workers) {
for (int j = i + 1; j < ptCount; j++) {
// Check the squared distance.
int dx = ptList[i].x - ptList[j].x;
int dy = ptList[i].y - ptList[j].y;
if (dx*dx + dy*dy <= dsq) {
c++;
}
}
}
ssize_t written = write(fd[WRITE], &c, sizeof(c));
if (written == -1)
perror("write error");
if (written != sizeof(c))
fail("Write failed on pipe");
exit(0);
}
}
if (close(fd[WRITE]) < 0)
fail("Error closing pipe's write channel");
int d;
ssize_t r;
while ((r = read(fd[READ], &d, sizeof(d))) > 0) {
if (r != sizeof(d))
fail("read error");
total += d;
}
请注意,这里我们必须在开始读取之前显式关闭管道的写入通道。 这是为了避免在不再有子进程正在主动写入管道时挂起父进程。 请记住,只要在管道的写通道打开的情况下至少存在一个进程,读操作就会阻塞。 如果父进程使写通道保持打开状态,则read(2)
将永远不会返回,因为父进程自己有可能向管道中写入数据(即使我们知道不会)。 因此,我们必须关闭fd[WRITE]
。
另外,由于我们知道确实有需要从管道读取的workers
编号,因此我们可以在循环之后执行此操作,而不用关闭写入通道:
int d;
int i;
for (i = 0; i < workers; i++) {
if (read(fd[READ], &d, sizeof(d)) != sizeof(d))
fail("Failed to read from pipe");
total += d;
}
其他一些(不相关的)备注:
distance
在argv[1]
, workers
程序在argv[2]
,但是传递给fail()
的错误消息似乎表明distance
在argv[2]
。 argv[1]
被解析为两次整数: atoi(3)
和sscanf(3)
。 我会坚持使用sscanf(3)
因为您可以检查返回值以确保解析成功。 workers
没有经过验证,并使用atoi(3)
转换。 错误将被忽略。 我建议像使用distance
一样使用sscanf(3)
对其进行解析,并确保它成功。 pid
的正确类型是pid_t
,而不是int
。 请使用正确的类型(除了unistd.h
之外,您可能还必须包含sys/types.h
)。 这是整理出所有这些的最终版本:
int main(int argc, char *argv[]) {
int distance;
int workers;
if (argc != 3 || sscanf(argv[1], "%d", &distance) != 1 || sscanf(argv[2], "%d", &workers) != 1)
fail("usage: <distance> <workers>");
readPoints();
// Compute the square of the distance bound, since that's what we'll
// need to compare against.
int dsq = distance * distance;
// Count up the number of nearby pairs of points.
int total = 0;
int fd[2]; // pipe
if (pipe(fd) != 0)
fail("Can't create pipe");
pid_t pid;
int chNum; // child's number
int c;
for (chNum = 0; chNum < workers; chNum++) {
c = 0;
pid = fork();
if (pid == -1)
fail("Can't create child process");
if (pid == 0) { // it's a child
for (int i = chNum; i < ptCount; i += workers) {
for (int j = i + 1; j < ptCount; j++) {
// Check the squared distance.
int dx = ptList[i].x - ptList[j].x;
int dy = ptList[i].y - ptList[j].y;
if (dx*dx + dy*dy <= dsq) {
c++;
}
}
}
ssize_t written = write(fd[WRITE], &c, sizeof(c));
if (written == -1)
perror("write error");
if (written != sizeof(c))
fail("Write failed on pipe");
exit(0);
}
}
if (close(fd[WRITE]) < 0)
fail("Error closing pipe's write channel");
int d;
ssize_t r;
while ((r = read(fd[READ], &d, sizeof(d))) > 0) {
if (r != sizeof(d))
fail("read error");
total += d;
}
printf("Total: %d\n", total);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.