dubyaa
dubyaa

Reputation: 199

C execv() parameter issue

I cannot get execv() to work in my C program. I suspect the problem is in this segment, something having to do with char* args[10]. Here is the segment:

  void mySystem(char *str, int *num_f, int *sig_k)  {
   int pid, stat;

   if ( fork() == 0)  {
    char * args[10];
    args[0] = str;
    args[1] = NULL;

    execv(str, &args);
    exit(20);

This gives a warning of:

systest.c:17: warning: passing argument 2 of âexecvâ from incompatible pointer type

I have been working for hours, and tried seemingly everything. What is going on? Here is all the code, just for reference incase I am making an unrelated error:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>


void mySystem(char *str, int *num_f, int *sig_k)  {
   int pid, stat;

   if ( fork() == 0)  {

        char * args[10];
        args[0] = str;
        args[1] = NULL;

        execv(str, &args);
        exit(20);               
   }

   pid = wait(&stat);
   if (WEXITSTATUS(stat) != 0)  {
        printf("command %s failed (exit code %d)\n", str, WEXITSTATUS(stat));
   } else {
        printf("command %s success (exit code 0)\n", str);
        num_f += 1;
        printf("wat %d\n", num_f);
   }


}       //mySystem



int main() {

   char buf[100];
   char cmd[100];       
   int num_fails = 0, sig_kills = 0;

   while(fgets(buf, 100, stdin)){
        sscanf(buf, "%s", cmd);
        if (strcmp(cmd, "quit") == 0) {
                printf("ran with %s\n", cmd);
                printf("num success = %d\n",num_fails);
                exit(0);        //returns 0 if equal, 1 if not
         }

printf("in main %s\n", cmd); 
        mySystem(cmd, &num_fails, &sig_kills);
   } 


return 0;

}

When ran, all commands just fail. Any help is greatly appreciated.

Upvotes: 0

Views: 6728

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409166

What execv wants is a char *[], i.e. an array of pointer, which is what you define with args.

If you add the & to args you get the type char *(*[]), that is a pointer to an array of pointers. Skip the & in the execv call and it will all work.

Upvotes: 1

user529758
user529758

Reputation:

You're passing a char * * * for execv as the second parameter, while it accepts a char **. You don't need the addressof (&) operator, since array can only be passed by reference, not by value. So you want:

execv(str, args);

instead of

execv(str, &args);

Upvotes: 2

Related Questions