Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 使用管道时的分段故障_C_Fork_Pipe_Ipc - Fatal编程技术网

C 使用管道时的分段故障

C 使用管道时的分段故障,c,fork,pipe,ipc,C,Fork,Pipe,Ipc,我在做一项作业,要求用10个并行进程求两个数组的和,所以我写了这段代码,我习惯于在父进程和它的子进程之间通过管道到IPC,但当它想从管道读取数据时,它会给我分段错误 #include <stdlib.h> #include<stdio.h> struct s { int * x ; int max , min ; } ; void sum(int *a , int *b , struct s w , int min , int max , int pipe) {

我在做一项作业,要求用10个并行进程求两个数组的和,所以我写了这段代码,我习惯于在父进程和它的子进程之间通过管道到IPC,但当它想从管道读取数据时,它会给我分段错误

#include <stdlib.h>
#include<stdio.h>
struct s {
int * x ;
int max , min ;
} ;
void sum(int *a , int *b , struct s w , int min , int max , int pipe)
{
    int i ;
    for(i = min ; i < max ; i++)
    {
        *(w.x+i) = *(a+i)+*(b+i) ; 
    }
    write(pipe , w , sizeof(w)) ;
}
int main()
{
    int i ,min = 0 ,max = 1 ;
    int a[11] = {1,1,1,10,1,1,1,1,1,1,1} ; 
    int b[11] = {1,1,1,10,1,1,1,1,1,1,1} ;
    int c[11]; 
    int fd[2] ;
    int j ; 
    pipe(fd) ; 
    for(i =  0 ; i < 10 ; i++)
    {
        int pid = fork();
        if(pid == 0)
        {
            struct s w ;
            w.max = max ;
            w.min = min ;
            *w.x = c[0] ;
            close(fd[0]) ; 
            sum(a,b,w,min , max , fd[1]);
            printf("Done %d \n" , i);
            exit(0);
        }
        else
        {
            min++;max++;
        }
    }
    struct s w ; 
    for(j = 0 ; j < 10 ; j++)
    {
        //segmentation fault !!
        read(fd[0] , w ,sizeof(struct s)) ;
        for(i =  w.min ; i < w.max ; i++)
        {
            printf("[%d] --> %d \n" ,i , *(w.x+i) ) ;
        }
    }   
    return 0; 
}
#包括
#包括
结构{
int*x;
int max,min;
} ;
无效和(int*a、int*b、结构SW、int-min、int-max、int-pipe)
{
int i;
对于(i=min;i%d\n”,i,*(w.x+i));
}
}   
返回0;
}
有什么想法吗

read()第二个参数需要一个地址。对
w
的地址使用&operator

read(fd[0] , &w ,sizeof(struct s)) ;

您应该将
&w
传递到
读取
;不是
w
。那是怎么编译的?哪种编译器以静默方式将结构实例转换为指针?我就是做不到。你可能希望总是打开所有警告(
-Wall-Wextra-pedantic
用于gcc),然后修复你的代码,直到不再出现任何警告。好吧,它仍然会给我同样的问题!