Linux系统编程篇—进程(六)system函数、popen函数

system函数

system(执行shell 命令)

封装好的exec函数

相关函数

fork,execve,waitpid,popen

表头文件

#include<stdlib.h>

定义函数

int system(const char * string);

函数说明

system()会调用fork()产生子进程,由子进程来调用/bin/sh-c string来执行参数string字符串所代表的命令,此命令执行完后随即返回原调用的进程。在调用system()期间SIGCHLD 信号会被暂时搁置,SIGINT和SIGQUIT 信号则会被忽略。

返回值

如果system()在调用/bin/sh时失败则返回127,其他失败原因返回-1。若参数string为空指针(NULL),则返回非零值。如果 system()调用成功则最后会返回执行shell命令后的返回值,但是此返回值也有可能为system()调用/bin/sh失败所返回的127,因此最好能再检查errno 来确认执行成功。

附加说明

在编写具有SUID/SGID权限的程序时请勿使用system(),system()会继承环境变量,通过环境变量可能会造成系统安全的问题。

实例:

此处源码与execl类似exec族函数
只需修改一行,将原来的execl("./configout",“configout”,NULL,NULL);换为system("./configout");

#include<stdio.h>
#include <unistd.h>
int main()
{
    
    
        int a= 0;
        int fork_r=0;
        while(1){
    
    
                printf("please input a num\n");
                printf("this is father,pid=%d\n",getpid());
                scanf("%d",&a);
                if(a==1){
    
    
                        fork_r=fork();
                        if(fork_r==0){
    
    
                                        sleep(2);
                                        printf("this is child,pid=%d\n",getpid());
                                        system("./configout");
                        }
                }else{
    
    
                        printf("waitting...\n");
                }
        }
        return 0;
}

popen函数

popen(执行shell 命令,同时可以获取运行的输出结果)

popen比system的优点是,popen可以获取运行的输出结果

需要包含的头文件
#include<stdio.h>
函数原型:

FILE popen( const char command, const char* mode )

参数说明:

command: 是一个指向以 NULL 结束的 shell 命令字符串的指针。这行命令将被传到 bin/sh 并使用 -c 标志,shell 将执行这个命令。
mode: 只能是读或者写中的一种,得到的返回值(标准 I/O 流)也具有和 type 相应的只读或只写类型。
如果 type 是 “r” 则文件指针连接到 command 的标准输出;
如果 type 是 “w” 则文件指针连接到 command 的标准输入。
int pclose (FILE* stream)

参数说明:

stream:popen返回的文件指针

返回值:

成功,则返回一个读或者打开文件的指针
失败,返回NULL,具体错误要根据errno判断

注意:

读取:需要使用fread()来读取popen产生的管道中的内容

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

关闭:popen() 函数用于创建一个管道:其内部实现为调用 fork 产生一个子进程,执行一个 shell 以运行命令来开启一个进程这个进程必须由 pclose() 函数关闭。

int fclose(FILE *fp);
实例:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
    
    
        char ret[1024]={
    
    0};
        FILE *fp=NULL;
        int nread=0;
        fp=popen("ps","r");
        nread=fread(ret,1,1024,fp);
        printf("read ret %d byte,ret=%s\n",nread,ret);
        pclose(fp);
        return 0;
}
实验结果:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44933419/article/details/112845433
今日推荐