linux--进程--system与popen函数

1.system

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

返回值:

        成功,则返回进程的状态值;不能源码execl函数,返回127;失败返回-1;

        不能成功运行分析文章:linux下system函数详解_linux system_遥_望的博客-CSDN博客

在linux系统下,system函数是execl函数的封装版

popen()函数较于system()函数的优势在于使用简单,popen()函数只返回两个值:成功 /失败

源码:

#include
#include
#include
#include

int system(const char * cmdstring)
{
  pid_t pid;
  int status;

  if(cmdstring == NULL){
      
      return (1);
  }


  if((pid = fork())<0){

        status = -1;
  }
  else if(pid == 0){
    execl("/bin/sh", "sh", "-c", cmdstring, (char *)0);
    -exit(127); //子进程正常执行则不会执行此语句
    }
  else{
        while(waitpid(pid, &status, 0) < 0){
          if(errno != EINTER){
            status = -1;
            break;
          }
        }
    }
    return status;
}

在linux系统下,system函数是execl函数的封装版
文中的 "sh -c ps"和我们所使用的"ps"是完全等价的

例子代码:

#include <stdio.h>
#include <stdlib.h>
int main()
{
   system("ps");
   printf("\n");
}

直接运行ps指令;

运行文件:

#include <stdio.h>
int main(int argc,char *argv[])
{
  int i;
  for(i=0;i<argc;i++){
     printf("argv[%d]:%s\n",i,argv[i]);
  }
  return 0;
}

system运行:

#include <stdio.h>
#include <stdlib.h>
int main()
{
   system("./test aa bb cc dd");
   printf("\n");
} 

结果:

    argv[0]:./test  //程序地址
    argv[1]:aa //以下为程序参数
    argv[2]:bb
    argv[3]:cc
    argv[4]:dd

还可以运行子进程中的其他程序:

在Linux文件编程中

写一个TEST.config文件:

SPEED=5
LENG=1
SCORE=90
LEVEL=95

对TEST.config文件内容进行修改,将LENG=1,改成LENG=5

代码:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
 
int main(int argc,char **argv)
{
    int fdsrc;
    char *readbuf=NULL;
    
    if(argc!=2){
        printf("pararm error\n");
        exit(-1);//tuichugaichengxu
    }
    
    //打开文件,将文件复制到readbuf中
    fdsrc=open(argv[1],O_RDWR);
    int size=lseek(fdsrc,0,SEEK_END);
    lseek(fdsrc,0,SEEK_SET);
 
    readbuf=(char *)malloc(sizeof(char)*size+8);
    int n_read=read(fdsrc,readbuf,size);
 
    //找到readbuf中LENG=中的位置,将位置移动到1,替换为5
    char *p=strstr(readbuf,"LENG=");
    if(p==NULL){
        printf("not found\n");
        exit(-1);
    }
    
    p=p+strlen("LENG=");
    *p='5';
 
    //移动光标到文件头,重新将readbuf中的内容写入到打开的文件中
    lseek(fdsrc,0,SEEK_SET);
    int n_write=write(fdsrc,readbuf,strlen(readbuf));
 
 
    close(fdsrc);
    return 0;
}


编译:gcc demo13.c

运行:./a.out TEST.config

运行结果为:

SPEED=5
LENG=5
SCORE=90
LEVEL=95

system运用:

将上述代码编译为./changedata

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
 
int main()
{
	pid_t pid;
	int data=10;
 
	
	while(1){
		printf("please input a data\n");
		scanf("%d",&data);
		if(data==1){
			pid=fork();
			if(pid>0){
				wait(NULL);
			}
			if(pid==0){
//				execl("./changedata","changedata","config.txt",NULL);
				system("./changedata config.txt");
				exit(0);
			}
		}
		else{
			printf("wait,do nothing\n");	
		}
 
	}
 
 
	return 0;
}

cat config.txt

能够发现LENG=1变成了LENG=5

要注意的是,system运行完后,父进程还会继续向下运行,这点与execl函数不同。

2.popen函数

popen的使用:

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

 command:是一个指向以NULL结束的shell命令字符串的指针。

type:只能是读或写的其中一种r/w

无法获得system的值,需要使用popen
 

代码:

#include <stdio.h>


int main()
{
        char ret[500]={0};
        FILE *fp;
        fp = popen("ps","r");
        int n_read = fread(ret,1,1024,fp);
        printf("read ret = %d byte\n ret =\n %s\n",n_read,ret);



        return 0;
}

结果:

当使用system时,ret的值无法读出,用popen函数;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
fork-popen和system都是用来创建进程函数。 fork函数是用于创建一个新的进程,新进程完全复制了父进程的资源。子进程可以通过返回值来区分自己是子进程还是父进程。fork函数相当于同时调用了fork、exec和waitpid这三个系统调用,会等待子进程执行完成后再继续执行。而popen函数则是通过管道来启动一个进程,并返回一个文件指针,可以用来读取或写入子进程的输入输出。popen函数不需要等待子进程执行完成就可以返回。 系统提供的system函数是用于执行shell命令的。它的原型是`int system(const char* command)`,可以通过传入shell命令作为参数来执行命令。system函数会一直等待shell命令执行完成(waitpid),然后返回。而popen函数则可以并行执行shell命令,不需要等待命令执行完成。 在使用popen函数后,需要调用pclose来对所创建的子进程进行回收,否则可能会导致僵尸进程的情况。 总结起来,fork-popen和system都是用来创建进程函数,但是fork-popen是并行执行的,而system是串行执行的。同时,在使用popen函数后,需要调用pclose进行子进程回收。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [Linux---popen、system函数](https://blog.csdn.net/y6_xiamo/article/details/80156598)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [重新实现popen和system函数](https://download.csdn.net/download/u013105439/10441160)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值