levijoraan levijoraan - 1 year ago 74
C Question

Error when trying to sum a file and transfer through pipe/fork/process?

I am trying to pass information from the child process to the parent process in this program. Here's the code so far, still working on cleaning it up:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

main() {

char *s, buf[1024];
int fds[2];
int sum;
s = "Hello world!\n";
FILE *file;

printf("child process: \n");
int c;
int number;
sum = 0;

file = fopen("file1.dat", "r");
if (file) {
while ((c = getc(file)) != EOF){
printf("child process: step 1");



It is compiling correctly and without error, but is returning the number 6 followed by a bunch of unrecognized characters (question marks) when I run it.

What could I be missing? My senses tell me something with the read.

Edit: I should add that my intent is for the child process to open and read the file (which contains multiple lines of numbers) and add them up, and return the total to the parent process.

Answer Source

Assuming sizeof(int) == 4, you wrote 12 arbitrary bytes (4 of which represent the int value of sum — the other 8 bytes giving undefined behaviour since they're not part of 'the same array' as sum) onto the pipe, and then you read them into buf. Then you try to print the arbitrary bytes to standard output with write().

You don't check for any errors; you should.

You do need to convert the bytes back into an ASCII digit stream to make sense of the value. You should use write(fds[1], &sum, sizeof(sum)) to write, and read(fds[0], &sum, sizeof(sum)) to read, and then you can print with printf("%d\n", sum);. Or you can do the conversion yourself and still use write() to print the converted string. Or you can do the conversion of sum to a string of digits in the child. Or …

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download