C 使用多个进程读取文件并通过管道发送数字()

C 使用多个进程读取文件并通过管道发送数字(),c,for-loop,pipe,fork,child-process,C,For Loop,Pipe,Fork,Child Process,我必须使用fork(2)生成用户输入的尽可能多的子项 然后,我需要他们分开工作,读取坐标点的txt文件,将它们之间的距离与输入的距离进行比较 然后,他们将给定距离内的点数相加。每个孩子必须将他们的计数写入管道,家长必须读取每个计数并将其添加到总数中,然后打印出来。这是我的密码: int main( int argc, char *argv[] ) { int distance = atoi(argv[1]); if ( argc != 3 || sscanf( argv[ 1 ],

我必须使用
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;
 }
intmain(intargc,char*argv[]){
int-distance=atoi(argv[1]);
如果(argc!=3 | | sscanf(argv[1]、%d”、&distance)!=1)
失败(“用法:对”);
阅读点();
int-workers=atoi(argv[2]);
//计算距离界的平方,因为这就是我们要计算的
//需要与之比较。
int dsq=距离*距离;
//数一数附近的几对点。
int-total=0;
int fd[2];//管道
如果(管道(fd)!=0){
失败(“无法创建管道”);
}
int-pid;//子对象
int chNum;//孩子的号码
INTC;
对于(chNum=0;chNum0){
等待(空);
printf(“总计:%d\n”,总计);
}
返回0;
}
我使用for循环使子对象具有
fork(2)
,然后我让他们计算计数并将其发送到管道,供家长读取。家长读取
d
并将其添加到
total
。我想知道我是否正确使用管道将每个孩子的计数发送给家长和/或我是否正确分叉,因此它只来自一个家长。我正在获取wr当我使用多个子项时,总计数为ong


如果我使用1个child,总结果是166428,这是正确的,但如果我使用4个child,则结果是164908。有人能帮我吗?

你没有正确处理管道

首先,您不需要锁定/解锁来写入和读取管道:小于
pipe\u BUF
字节的写入保证是原子的。POSIX.1-2001要求
pipe\u BUF
至少为512字节;因为您一次只写入
sizeof(int)
字节,所以您是安全的(除非
sizeof(int))
大于或等于512,这是胡说八道)。请参阅路径名变量值下的
人工限制.h

{PIPE_BUF}

保证为原子的最大字节数 写入管道时。可接受的最小值:{u 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[写入] <代码>:考虑下一次迭代中发生什么,当您拨下一个进程时,下一个循环中的子进程将尝试写入已经关闭的文件描述符,因此发生错误(和<代码>写入(2))。使用
EBADF
失败,但您从未检查
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;
    }

}
请注意,在这里,我们必须在开始读取之前显式关闭管道的写入通道;这是为了避免在没有更多的子进程正在积极写入管道时父进程挂起。请记住,只要至少有一个进程的写入通道打开,读取就会阻塞。如果父进程保持写入通道annel open,
read(2)
将永远不会返回,因为父级本身可能会写入管道(即使我们知道它不会)。因此我们必须关闭
fd[write]

或者,由于我们知道有确切的
工作者
编号要从管道中读取,因此我们可以在循环结束后执行此操作,而不是关闭写入通道:

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;
}

你没有正确处理管道

首先,您不需要锁定/解锁来写入和读取管道:小于
pipe\u BUF
字节的写入保证是原子的。POSIX.1-2001要求
pipe\u BUF
至少为512字节;因为您一次只写入
sizeof(int)
字节,所以您是安全的(除非
sizeof(int))
大于或等于512,这是胡说八道)。请参阅路径名变量值下的
人工限制.h

{PIPE_BUF}

保证为原子的最大字节数 写入管道时。可接受的最小值:{u POSIX_pipe_BUF}

这本身简化了代码并减少了不必要的锁定/解锁
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;
}
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;
}