system()函数、popen()函数的使用

  1. system()函数

  • system函数和exec函数一样,都是执行shell 命令,但是system比较顶,把execl函数封装起来,所以习惯上使用system函数

  • system函数具体功能是调用windows操作系统下的C语言应用

#include <stdlib.h>
 
int system(const char *command);
 
const char *command:参数字符串command为命令名
 
返回值:
        成功,则返回进程的状态值;
        当sh不能执行时,返回127;
        失败返回-1;

2.函数返回值

(1)=-1:出现错误  

(2)=0:调用成功但是没有出现子进程     

(3)>0:成功退出的子进程的id

  • 如果system()调用成功则最后会返回执行shell命令后的返回值,但是此返回值也有可能为system()调用/bin/sh失败所返回的127,因此最好能再检查errno来确认执行成功

  • 如果system()在调用/bin/sh时失败则返回127,其他失败原因返回-1。

举例:

#include <stdio.h>
#include <unistd.h>
 
int main(){
 
        if(system("ps") == -1){ //调用ps应用
                printf("system filed!\n");
                perror("why");
        }
        printf("Execute after failure!\n");
        return 0;
}

执行结果:

3.popen()函数

1.popen()可以执行shell命令,并读取此命令的返回值;
2.p open函数 比system在实际应用中的好处可以获得运行的输出结果。
3 .popen()函数通过创建一个管道,调用fork()产生一个子进程,执行一个shell以运行命令来开启一个进程。可以通过这个管道执行标准输入输出操作。这个管道必须由pclose()函数关闭,必须由pclose()函数关闭,必须由pclose()函数关闭,而不是fclose()函数(若使用fclose则会产生僵尸进程)。
NAME
       popen, pclose - pipe stream to or from a process
 
SYNOPSIS
       #include <stdio.h>
 
       FILE *popen(const char *command, const char *type);
 
const char *command:参数字符串command为命令名
const char *type:   执行文件的权限,如"w"或"r"

#include <stdio.h>
#include <unistd.h>
 
int main(){
 
        FILE *fp;
        char readBuf[1024] = {0};
 
        fp = popen("ps","r"); //调用popen去执行ps,执行结果会流到popen开辟的管道fp当中
 
        int n_read = fread(readBuf,1,1024,fp);  //读取fp管道中的内容到readBuf
 
        printf("read n_read %d byte,readBuf = %s\n",n_read,readBuf);
        return 0;
}

执行结果:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值