linux c语言执行shell命令

system 函数原型

int system(const char *command)

函数说明

输入command指的是要执行的shell命令。

popen()/pclose()函数原型

FILE *popen(const char *command, const char *type);
int pclose(FILE *stream);

函数原理

popen函数是首先fork一个子进程,然后exec,执行一个shell,在这个shell中执行参数command命令。参数type 可读r,可写w,不能同时。rw和r一样。使用完之后记得使用pclose关闭。

例子1:读取执行命令的返回值

void print_result(FILE *fp)  
{  
    char buf[100];  

    if(!fp) {  
            return;  
    }  
    printf("\n>>>\n");  
     while(memset(buf, 0, sizeof(buf)), fgets(buf, sizeof(buf) - 1, fp) != 0 ) {  
            printf("%s", buf);  
    }  
    printf("\n<<<\n");  
}  
  
int main(void)  
{  
    FILE *fp = NULL;  

    fp = NULL;  
    fp = popen("ntpdate time.pool.aliyun.com", "r");  //执行命令
    if(!fp)
    {  
        perror("popen");  
        exit(EXIT_FAILURE);  
    }  
    print_result(fp);  
    pclose(fp);  
    return 0;
}

例子2:system和popen()函数对比使用

#include <stdio.h>
#include <stdlib.h>

#define BUF_LEN 128
void cmd_exec(const char* cmd,char*result)
{
    FILE *fp = NULL;  
    
    if(result == NULL)
        return;
    
    fp = popen(cmd,"r");
    if(!fp)
    {  
        perror("popen");  
        exit(EXIT_FAILURE);  
    }  
    
    while(fgets(result, BUF_LEN, fp) != 0 )
    {  
//        printf("%s", result);  
    }  
    pclose(fp);  
}


int main(void)  
{          
    char buf[BUF_LEN] = {0};  
    int ret = 0;
   
    ret =  system("ntpdate time.pool.aliyun.com");
    printf("ret = %d",ret);  
    cmd_exec("echo $?",buf);
    printf("echo result %s",buf);
    
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值