• [shell]system和execlp简单示例


    shell脚本:hello.sh

    #!/bin/bash
    echo "i am in shell script"
    echo "param 1 is $1"
    echo "param 2 is $2"
    variable=$[ $1 + $2 ]
    echo "sum is $variable"

    system接口:system.c

    #include <stdio.h>
    #include <stdlib.h>
    #include <fcntl.h>
    
    void main(void)
    {
        printf("i am in c code!
    "
        system("/bin/bash ./hello.sh 10 20);  
    }

    输出

    i am in c code!
    i am in shell script!
    param 1 is 10
    param 2 is 20
    sum is 30

     execlp接口:execlp.c

    #include <stdio.h>
    #include <stdlib.h>
    #include <fcntl.h>
    #include <unistd.h>
    
    void main(void)
    {
        int ret = 0;
        int param1 = 10;
        int param2 = 20;
    
        printf("i am in c code!
    ");
        if(fork() == 0)
        {
            printf("execlp...........
    ");
            ret = execlp("/bin/bash", "bash", "hello.sh", &param1, &param2, NULL);
            if(ret < 0)
            {
                 printf("execlp failed!
    ");
                 return;
             }
        }  
    }

    这其中execlp的参数不管怎么填都得不到正确运行的结果

    使用system获取system本身的返回值和脚本的返回值

    int system_func(const char *command)
    {
        int status;
        int ret;
        
        status = system(command);
    #ifdef DEBUG    
        printf("status is 0x%x
    ", status);
    #endif
        if(-1 == status)
        {
            printf("%s:system error
    ", __FUNCTION__);
            return -1;
        }
        else
        {
            if(WIFEXITED(status))
            {
                if(0 == WEXITSTATUS(status))
                {
                    ret = (status>>8)&0xFF;
                    return ret;
                }
                else
                {
                    printf("%s:run shell script fail, script exit code:%d
    ", __FUNCTION__, WEXITSTATUS(status));
                    return -1;
                }
            }
            else
            {
                printf("%s:system fail, exit status=%d
    ", __FUNCTION__, WEXITSTATUS(status));
                return -1;
            }
        }
    }
  • 相关阅读:
    mybatis和spring整合
    Freemarker教程1(基本使用)
    mybatis教程6(逆向工程)
    mybatis教程4(动态SQL)
    mybatis教程5(延迟加载和缓存)
    mybatis教程2(配置文件)
    python作用域
    软件测试基础面试题
    http协议
    selenium自动化测试
  • 原文地址:https://www.cnblogs.com/aaronLinux/p/6910727.html
Copyright © 2020-2023  润新知