Providing arguments using standard input and error

I am trying to write a program which invokes a custom command to add two numbers.
The addition function reads from standard input stream 0, input stream 3 and outputs to standard output 1.

I try to write to and read from these streams to provide arguments and retrieve results but it does not work.

This is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstdlib>

using namespace std;

int main()
{

        int x = 1;
        int y = 4;
        int z = 0;

        write(0, (char *)&x, sizeof(int));
        write(3, (char *)&y, sizeof(int));
        execl("addition", "addition", (char*)0);
        read(1, (char *)&z, sizeof(int));
        z = z - '0';
        cout<<z;
}


Code for addition:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstdlib>

using namespace std;

main(int argc, char *argv[])
{
	int x, y, z;
	while (read(0, (char *)&x, sizeof(int)) && read(3, (char *)&y, sizeof(int))) {
		z = x + y;

		write(1, (char *)&z, sizeof(int));
	}
}	


When I run this it does not work. It should just print out z instantly but it waits for me to type something in and prints out gibberish like …@5…@6 when I press enter. I have to force exit to make it stop.

What am I doing wrong?
write(3, ...
What's 3?
Last edited on
prints out gibberish

You should convert an int value into a character representation before printing if you want human readable numbers.

You may also want to check return code of read() to detect f.e. end-of-file condition. See your manual page for details.
Topic archived. No new replies allowed.