system与popen函数的使用

本文介绍了C语言中用于执行shell命令的两个函数,system和popen。system函数用于执行一个shell命令,返回进程状态值,而popen创建管道和子进程,允许读写命令的输出。示例中展示了如何使用这两个函数执行date命令,并捕获其输出。popen与system的区别在于它可以与流文件交互,获取命令执行的结果。

一、system的使用

作用:执行一个shell指令
原型:

NAME
       system - execute a shell command

SYNOPSIS
       #include <stdlib.h>

       int system(const char *command);

参数说明:

command:可执行指令

返回值:

成功,则返回进程的状态值;
当sh不能执行时,返回127;
失败返回-1;

执行指令的两种方式:
1.在终端输入:./a.out
2. sh -c ./a.out
system的作用跟exec一样,是因为system的源码中调用了execl(“/bin/sh”,“sh”,“-c”,cmd,NULL);

实例:用system函数执行date指令
#include <stdlib.h>
#include <stdio.h>
// int system(const char *command);
int  main()
{
        printf("date is:\n");
        system("date");
        return 0;
}
~  

执行效果:
在这里插入图片描述

二、popen的使用

作用:

popen是计算机科学中的进程I/O函数,与pclose函数一起使用,功能是通过创建一个管道,调用 fork 产生一个子进程,执行一个 shell 以运行命令来开启一个进程。
与system不同之处:
popen可以写到一个流文件里,可以获取运行结果。
原型:

       #include <stdio.h>

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

       int pclose(FILE *stream);

参数说明:

command:可执行指令
type:参数只能是读或者写中的一种,得到的返回值(标准 I/O 流)也具有和 type 相应的只读或只写类型。如果 type 是 “r” 则文件指针连接到 command 的标准输出;如果 type 是 “w” 则文件指针连接到 command 的标准输入。

返回值:

如果调用 fork() 或 pipe() 失败,或者不能分配内存将返回NULL,否则返回标准 I/O 流。
返回错误:
popen 没有为内存分配失败设置 errno 值。
如果调用 fork() 或 pipe() 时出现错误,errno 被设为相应的错误类型。
如果 type 参数不合法,errno将返回EINVAL。

实例:用system函数执行date指令,并读到buff里
#include <stdio.h>
#include <string.h>
// int system(const char *command);
int  main()
{
        FILE *fp;
        int nread;
        char buff[1024];memset(buff,0,sizeof(buff));
        fp = popen("date","r");
        //size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
        nread = fread(buff,1,1024,fp);
        printf("read %d byte,buff:%s\n",nread,buff);
        pclose(fp);
        return 0;
}

执行效果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值