Linux进程之API(下)(system、popen)

目录

一、system函数

二、popen函数


一、system函数

        作用:调用其他程序。

#include <stdlib.h>

int system(const char *command);


##const char *command   程序调用命令字符串
##system()函数的返回值如下:
##成功则返回进程状态码
##当sh不能执行时,返回127
##失败返回-1
#include <stdlib.h>
#include <unistd.h>


int main(void)
{
    printf("before execl\n");
    char *argv[]={"ps",NULL,NULL};
    if(system("ps") == -1)//调用system执行ps命令
    {
        printf("execl failed!\n");
        perror("why");
    }
    printf("after execl\n");
    return 0;
}

 成功调用ps程序,而且相对于exec函数,system还会继续执行下面的代码。

二、popen函数

作用:调用其他程序。

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

#include <stdio.h>

FILE *popen(const char *command, const char *type);



##返回值:文件流
##const char *command :运行程序的命令字符串
##const char *type    :执行权限,r或w
##如果 type 是 “r” 则文件指针连接到 command 的标准输出;
##如果 type 是 “w” 则文件指针连接到 ##command 的标准输入。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>


int main(void)
{   FILE *fp;
    char str[1024]={0};
    fp=popen("ps","r");//命令执行ps,权限r
    int nread= fread(str,1,1024,fp);//使用fread读取文件流数据,nread返回读取到的字节
    printf("have %d char,context is %s\n",nread,str);//输出字符个数,以及内容



     return 0;
}

执行结果:

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值