The new forums will be named Coin Return (based on the most recent vote)! You can check on the status and timeline of the transition to the new forums here.
The Guiding Principles and New Rules document is now in effect.

C Programming - Can't Get execv() to Print Output

Patches7o9Patches7o9 Registered User regular
edited June 2007 in Help / Advice Forum
Ok, so I have a Factorial program that works fine, outside of things not related to this problem. It takes a single command line arg and prints out the Factorial of that number. If you try entering more than one command line arg it scolds you and ends.

I have another program that uses execv() to run the Factorial program (It's actually part of a bigger program, but the only part of it that won't work is the execv() part). If I use execv("./factorial", NULL) it scolds me, as it should, and ends. But if use execv("./factorial", 10) it doesn't print anything.

Any ideas why?

Here's my simple program to get exec to run something.
#include <stdio.h>
#include <stdlib.h>

main(int argc, char* argv[])
{
      execv("./factorial", 10);
}
Here's my factorial program.
#include <stdio.h>

main(int argc, char *argv[])
{
   int x;
   if (argc == 2){
     x = atoi(argv[1]);
	 printf("&#37;d\n", factorial(x));
   }
   else printf("Please run this program with a single integer variable. ie. factorial 10 \n");
}

int factorial(int fac){
   if (fac != 1)
      return fac * factorial(fac - 1);
   else return 1;
}

Patches7o9 on

Posts

  • JaninJanin Registered User regular
    edited June 2007
    1) Always turn on full warnings for your compiler. In GCC, you'd use the flags -Wall -Wextra -ansi -pedantic

    which warned me you didn't...
    2) Check the return values of system calls for errors, and use perror to get the detailed error message.

    and the message told me that...
    3) You are using execv incorrectly. Please read the man page for the function signature.

    Here's a corrected version of the main program. The factorial program has some errors also, but enabling warnings should tell you them.
    #include <unistd.h>
    #include <stdio.h>
    
    int
    main(int argc, char* argv[])
    {
          /* List of arguments. Every argument must be a character string */
          char *new_args[] = {"factorial" /* argv[0] */,
                              "10"        /* argv[1] */,
                              NULL        /* NULL terminates the argument list */};
    
          /* Pass in list of arguments */
          if (execv("./factorial", new_args) < 0)
          {   
            /* Check for an error condition */
            perror ("execv");
          }   
          return 0;
    }
    

    Janin on
    [SIGPIC][/SIGPIC]
  • Patches7o9Patches7o9 Registered User regular
    edited June 2007
    Wow. Thanks. I really appreciate the help. I'll make sure to use those warnings from now on.

    Patches7o9 on
Sign In or Register to comment.