简体   繁体   中英

How does this C program work?

void child(int *fd) {
    int j , x; 
    for(j = 0; j < 10; j ++) {
        scanf ("%d", &x);
        if(x % 2 != 0)
            write(fd[1], sizeof(int), &x);
    }
    close (fd[1]);
}

void parent(int *fd) {
    int v, r = 0;
    while(read(fd[0], sizeof(int), &v) != 0)
        r = r + v;
    printf("%d\n", r);
}

int main(void) {
    int s, fd[2];
    pipe(fd);
    s = fork();
    if(s == 0)
        child(fd);
    else parent(fd);
}

I think that the above program create a pipe fd and place two file descriptors, one each into the arguments fd[0] and fd[1] ==> then It create a new process

  • It launch the child function if s = 0 ==> the program input 10 integers ==> if an integer is odd ==> It write &x bytes from the buffer pointed to by sizeof(int) to the file associated with the open file descriptor, fd[1] ==> it deallocate the file descriptor indicated by fd[1]

  • It launch the parent function if s != 0 ==> if &v = 0 ==> it displays the value of &v.

But I still not sure about how this program works, please feel free to correct or to give more details. Thank for the help !

You're close.

Your description of how the child process works is correct.

The parent process reads each number from the pipe. It's not testing whether z is 0, it's testing whether read returns 0, which it does when it has reached EOF (ie the child has closed the pipe). And it's not displaying the value of &z , it's adding up all the values of z and displaying the total when it reaches the end.

As written, the code is a bit odd because the second and third parameters of the read and write functions seem backwards. It's just weird to "write &y bytes from the buffer pointed to by sizeof(int)" because sizeof() anything isn't a buffer.

If you swap those two, then the child process reads integers from the console and writes the odd ones to a pipe back to the parent, who reads them, sums them and prints the sum at EOF.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM