arrayscexecvp

Executing a program arguments with C and evecvp failing to forward correctly


I am trying to execute a program with the execvp function within an overseer and client distributed system. The client sends a program to be executed with the arguments:

char buf[500];
int bytes_recieved = 0;
char array[1][26];
bytes_recieved = recv(clientfd, buf, 5000, 0);
buf[bytes_recieved] = '\0';

char buf1[50];
int bytes_recieved1 = 0;
char *array1[4];

for (int i = 0; i < 3; i++){
   bytes_recieved1 = recv(clientfd, buf1, 50, 0);
   array1[i] = buf1;
   printf("%s = buffer\n", buf1);
} 
buf1[bytes_recieved] = '\0';

if(bytes_recieved != -1){
   printTime();
   fprintf(stdout,"atempting to execute program: %s\n", buf);
   if(execvp(buf, array1) == -1) {
      return 1;
   }
}

I'm stuck on trying to figure out what happens when I print out the array of arguments in the program the last argument is the same for all of them? for example I run this in the client program to be executed:

./client 12345 home/user/test_program 1 2 3

the result from a simple printf is:

3
3
3

When I manually assign each argument in the array in the overseer:

array1[0] = "1";
array1[1] = "2";
array1[2] = "3";

and send it to the executed program it prints correctly.

I have also tested that the received buffer from the file descriptor is correctly assigning the variables in the array:

 printf("%s = buffer\n", array1[i]);

within the assignment for loop, which returns:

    1 = buffer
    2 = buffer
    3 = buffer 

What am I doing wrong? Let me know if you need any more information.


Solution

  • This is some skeletal code, based on your code fragment. I can't test it — you did not provide an MCVE (Minimal, Complete, Verifiable Example — or MRE or whatever name SO now uses) or an SSCCE (Short, Self-Contained, Correct Example).

    char buf[500];
    int bytes_received = recv(clientfd, buf, sizeof(buf)-1, 0);
    if (bytes_received < 0)
        return 1;
    buf[bytes_received] = '\0';
    
    char *array1[5] = { buf };
    
    for (int i = 0; i < 3; i++)
    {
        char buf1[50];
        int bytes_received1 = recv(clientfd, buf1, sizeof(buf1)-1, 0);
        if (bytes_received1 < 0)
            return 1;
        buf1[bytes_received1] = '\0';
        array1[i + 1] = strdup(buf1);
        printf("argument = [%s]\n", buf1);
    }
    
    printTime();
    printf("atempting to execute program: %s\n", buf);
    for (int i = 0; array1[i] != NULL; i++)
        printf("argv[%d] = [%s]\n", i, array1[i]);
    fflush(0);
    execvp(array1[0], array1);
    fprintf(stderr, "failed to execute '%s'\n", array1[0]);
    return 1;
    

    Multiple changes include: