in reply to ARGV empty when calling Perl from C program

Hi,

there is a little difference between C's argv and @ARGV in Perl. argv in C has a first element representing the program called while @ARGV in Perl is the list of arguments after the Perl script. Have a look at:

#include <stdio.h> int main(int argc, char* argv[]) { printf("argc %d\n", argc); if(argc > 0) { printf("arg1 %s\n", argv[0]); } return(0); }

In Perl the name of the called script is in $0. So the C equivalent in Perl would be:

my @CARGV = ($0, @ARGV);

Regards
McA

Replies are listed 'Best First'.
Re^2: ARGV empty when calling Perl from C program
by Lotus1 (Vicar) on May 23, 2014 at 14:37 UTC

    http://www.gnu.org/software/libc/manual/html_node/Executing-a-File.html

    — Function: int execv (const char *filename, char *const argv[])

    The execv function executes the file named by filename as a new process image.

    The argv argument is an array of null-terminated strings that is used to provide a value for the argv argument to the main function of the program to be executed. The last element of this array must be a null pointer. By convention, the first element of this array is the file name of the program sans directory names. See Program Arguments, for full details on how programs can access these arguments.

    Since sending the program name for the first element of the array is only a convention, and the OP created his array with a number in the first element and passed it to execv wouldn't that get used? It seems like you could send whatever you like as the first element.

    Update:I did a test to see what would happen and the first element of the array passed to execv doesn't show up in the Perl script. Interesting.

    #include <stdio.h> void main(void) { char *temp[] = {"1", "2", "3", NULL}; printf("Hello from c\n"); execv( "./script.pl", temp ); printf("error"); }
    #!/usr/bin/perl use warnings; use strict; print ">>@ARGV<< from Perl\n"; __DATA__ pi@raspberrypi ~/Desktop/perlmonks $ ./hello Hello from c >>2 3<< from Perl
      thanks,this showed me the way.Perl was swallowing the very first argument and since I had just one followed by NULL, I could not see it

        I don't think Perl is doing it. I found this stackoverflow discussion where someone ran the unix program ps to show the running processes and it showed the value passed in argv[0] as the process name. So it looks like the os uses that first argument to allow you to have a nicer name than the full path it was invoked as.

        Thanks for posting the question, it was interesting to learn about and it got me to compile a c program for the first time in a long while, and on a Raspberry Pi at that.

      Look in $0

        I tried that and $0 contains ./script.pl. I don't know where the "1" from temp[0] went.