Run shell commands in Elixir

后端 未结 6 744
醉酒成梦
醉酒成梦 2020-12-14 05:23

I want to execute a program through my Elixir code. What is the method to call a shell command to a given string? Is there anything which isn\'t platform specific?

6条回答
  •  借酒劲吻你
    2020-12-14 06:05

    If I have the following c program in the file a.c:

    #include 
    #include 
    
    int main(int arc, char** argv)
    {
    
        printf("%s\n",argv[1]);
        printf("%s\n",argv[2]);
    
        int num1 = atoi(argv[1]);
        int num2 = atoi(argv[2]);
    
        return num1*num2;
    }
    

    and compile the program to the file a:

    ~/c_programs$ gcc a.c -o a
    

    then I can do:

    ~/c_programs$ ./a 3 5
    3
    5
    

    I can get the return value of main() like this:

    ~/c_programs$ echo $?
    15
    

    Similarly, in iex I can do this:

    iex(2)> {output, status} = System.cmd("./a", ["3", "5"])
    {"3\n5\n", 15}
    
    iex(3)> status
    15
    

    The second element of the tuple returned by System.cmd() is the return value of the main() function.

提交回复
热议问题