popen、system

简介: 1、popen函数  popen()通过创建一个管道,调用 fork 产生一个子进程,执行一个 shell 以运行命令来开启一个进程。这个进程必须由 pclose() 函数关闭,而不是 fclose() 函数。

1、popen函数

 popen()通过创建一个管道,调用 fork 产生一个子进程,执行一个 shell 以运行命令来开启一个进程。
这个进程必须由 pclose() 函数关闭,而不是 fclose() 函数。

#include <stdio.h>
FILE *popen(const char *command, const char *type);
int pclose(FILE *stream);

功能:执行shell命令,并读取此命令的返回值。
参数:command:一个指向以NULL结束的shell命令字符串的指针
      type:只能是读或写("r"或"w")
返回:如果调用fork()或pipe()失败,或者不能分配内存将返回NULL,否则返回标准I/O流



2、system函数

 system()会调用fork()产生子进程,由子进程来调用/bin/sh-c string来执行参数string字符串所代表的命令,此命令执行完后随即返回原调用的进程

#include <stdlib.h>
int system(const char *command);

函数:int system(const char *command)
功能:执行shell命令
参数:command:一个指向以NULL结束的shell命令字符串的指针
返回: -1 :fork()失败
    127 :exec()失败
   other:子shell的终止状态



3、例子

#include <stdio.h>
int main()
{
    FILE *fp   = NULL;
    char buf[100] = {0};
    fp = popen("cat /tmp/test", "r");
    if(NULL == fp)
    {
        printf("popen() erro!!!");
        return -1;
    }

    while(NULL != fgets(buf, sizeof(buf), fp))
    {
        printf("%s", buf);
    }

    pclose(fp);
    return 0;
}

fp = popen("date > /tmp/test", "w");
fwrite(buf, 1, sizeof(buf), fp);
目录
相关文章
|
5月前
System.exit(0)和System.exit(1)区别
System.exit(0)和System.exit(1)区别
|
5月前
|
Ubuntu Docker 容器
System has not been booted with systemd as init system (PID 1). Can‘t operate.
System has not been booted with systemd as init system (PID 1). Can‘t operate.
|
9月前
|
存储 Shell Python
Python中os.system()、subprocess.run()、call()、check_output()的用法
Python中os.system()、subprocess.run()、call()、check_output()的用法
179 0
|
Python
Python 技术篇-通过管道命令获取cmd执行的结果,获取os.system()、subprocess.Popen()执行命令返回的结果
Python 技术篇-通过管道命令获取cmd执行的结果,获取os.system()、subprocess.Popen()执行命令返回的结果
617 0
Python 技术篇-通过管道命令获取cmd执行的结果,获取os.system()、subprocess.Popen()执行命令返回的结果
|
Python
|
JavaScript 前端开发
|
开发工具 Perl