Declaring char array causes execv() to not work

前端 未结 1 549
日久生厌
日久生厌 2021-01-26 01:53

I wrote the following code in order to use pipes in c unix:

#include 
#include 
#include 
#include 

        
相关标签:
1条回答
  • 2021-01-26 02:34

    The parameter-array to go with calls to exec*() needs to be (char*)NULL-terminated.

    This line

    char* args[4]={"avg3.out","4","3","5"};
    

    should be

    char* args[] = {"avg3.out", "4", "3", "5", NULL};
    

    As it isn't in your code, exec() might get lost searching for it.

    By bad luck the stack might have been clean (0 filled) for the version of your code not declaring a and execv() found a NULL right after the pointer pointing to "5". Having a created on the stack then changed the content of the stack which made execv() getting lost searching for the NULL.


    Additionally its worth mentioning that the OP's code misses error checking on most of the relevant system call.

    Having done so together with a detailed examation of the errors' causes, probably by using calls to perror() might have led to solving this issue by providing relevant information.

    In particular placing it after the call to execv() it soon would have been obvious what's wrong:

     execv("avg3.out", args);
     perror("execv() failed");
    
    0 讨论(0)
提交回复
热议问题