0

I have program in C where I compute something and result of that (integer) I need to return back to parent process, but it returns wrong values.

For example app.cpp:

#include <stdio>

int main()
{
    int i = 53400;

    return i;
}

Parent process (in Perl language):

#!/usr/bin/perl
use strict;
use warnings;

my $res = system("./app");
print $res."\n";

If I return 0 in C, I get in parent process value of 0. If I return 1 in C, I get in parent process value of 256. If I return 2 in C, I get in parent process value of 512.

So I thought that it is just multiples by 256, but I was wrong because if I return 53400 in C, I get in parent process value of 38912 which is not multiple of 256.

So how can I get correct value from child process in parent?

tomsk
  • 967
  • 2
  • 13
  • 29
  • @Jean-FrançoisFabre what is solution? Because I need to return value back to parent process. – tomsk Nov 11 '19 at 21:44
  • 2
    `main()` return value won't be received by the parent process. You'd need to use some other mechanism to pass it, like IPC, files, shared memory, etc – SHG Nov 11 '19 at 21:44
  • 3
    According to [perldoc system](https://perldoc.perl.org/functions/system.html) : *"The return value is the exit status of the program as returned by the wait call. To get the actual exit value, shift right by eight."* – Håkon Hægland Nov 11 '19 at 21:47
  • @HåkonHægland if I shifted right by eight value `53400` in C, I got value `152` in Perl. – tomsk Nov 11 '19 at 21:53
  • 1
    @tomsk I think only return values between 0 and 255 are valid. It seems like the return value from the C program is logical `AND`ed with `0xff` – Håkon Hægland Nov 11 '19 at 21:59
  • @tomsk See also [What is the min and max values of exit codes in Linux?](https://unix.stackexchange.com/q/418784/45537) – Håkon Hægland Nov 11 '19 at 22:05
  • Im thinking what is easiest solution to return that value from child process back to parent, because I need it. – tomsk Nov 11 '19 at 22:13
  • 1
    @tomsk Maybe just push it to STDOUT: `std::cout << i;` from C++ and then use backticks in Perl: ```my $out = `./app` ``` to retrieve the output from the command – Håkon Hægland Nov 11 '19 at 22:38
  • (`printf("%d", i)` in C) – ikegami Nov 12 '19 at 09:09

0 Answers0