Linux_popen&&system

函数system
功能:封装fork(), waitpid(),exec(),实现*cmdstring的命令。

#include <stdlib.h>
int system(const char *cmdstring);
        //返回值:(见下)

(1)如果cmdstring是一个空指针,仅当命令处理程序可用时,返回0.
可以用这个确定这个操作系统是否支持system.UNIX系统中总是可用。
(2)system调用了fork、exec、waitpid,所以有3中返回值
如果exec失败,则返回值如同shell执行了exit(127)
如果3个函数都成功,返回值是shell的终止状态

int status;
if((status = system("date")) < 0 )
    err_sys("system() error");
pr_exit(status);    //分析status状态

这段代码运行相当于在shell输入了date命令,然后打印结束状态。
在函数内部,调用execl,如果失败,调用_exit(127),防止任一标准I/O缓冲在子进程被冲洗。

函数popen

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

popen执行command代码,结果输出到流,返回值为该流的描述符。
需用使用pclose关闭流。

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

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

    if(fp < 0) 
    {
        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("ls", "r");
    if(fp < 0) 
    {
        perror("popen");
        exit(EXIT_FAILURE);
    }
    print_result(fp);
    pclose(fp);
}

猜你喜欢

转载自blog.csdn.net/cute_shuai/article/details/80255617