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

目录

1、system()函数

2、popen()函数


1、system()函数

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

#include <stdlib.h>

int system(const char *command);

const char *command:参数字符串command为命令名

返回值:
        成功,则返回进程的状态值;
        当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;
}

执行结果:

2、popen()函数

popen()函数通过创建一个管道,调用fork()产生一个子进程,执行一个shell以运行命令来开启一个进程。

popen函数比system在应用中的好处:可以获取运行的输出结果

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;
}

执行结果:

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值