popen簡版實現思路-centos7.x

popen簡版實現思路

popen()能像打開文件(file)一樣打開進程(process),對進程進行類似於文件的讀read()寫write操作。

實現思路

  • popen()打開指定的進程,返回類似於進程的描述符的文件指針,通過對文件指針的操作進而實現進程件的交互(讀寫)。

這裏我們通過管道技術單擊查看)來實現popen()鏈接兩個進程的功能。
使用fdopen()來將管道的兩個端口(pipegate[0],pipegate[1])分別轉換成文件指針,並把需要的端口返回給調用pipe()的進程。

具體來說,就是在進程中創建一個進程,在兩個進程間創建一個管道,通過管道端口的文件指針來對管道進行讀寫,進而實現進程對進程的讀寫。

上代碼:
(單看實現思路,不考慮錯誤處理)

#ifndef POPENX_H
#define POPENX_H
/*
	author:wattercutter
	purpose:make a popen
	pro: popen.h(declear and define)
	what's in program: return a file ptr(FILE*) of a process for read and write in process
*/
#include<stdio.h>
#include<unistd.h>

FILE* popenx(const char* command,const char* mode)
{
	//pipegate for process
	int songate;
	int pargate;
	//mode for pipegate
	const int READ = 0;
	const int WRIET = 1;
	//judge the mode r/w
	if(*mode == 'w'){
	//if w then par-w,son-r
			songate = READ;
			pargate = WRITE;
	}
	else if(*mode == 'r'){
			songate = WRITE;
			pargate = READ;
	}else return NULL;
	
	//CREAT A PIPE
	int pipegate[2];
	pipe(pipegate);

	//CREAT A PROCESS
	int pid = fork();
	//par code - include return
	if(pid>0){
			close(pipegate[songate]);//close no necessary gate
			return fdopen(pipegate[pargate],mode);//return the file ptr(FILE*) of right gate
	}
	
	//son code - run the command exclp()
	close(pipegate[pargate]);
	dup2(pipegate[songate],songate);
	close(pipegate[songate]);
	//the first arg of execl needs total pathname,as execlp dose not need
	execl("/bin/bash","sh","-c",command,NULL);
	exit(1);
}
#ednif

這是我個人的代碼和註釋,如有興趣瞭解更多,可以先看看前面的“管道技術”鏈接,然後找找“exec”系列調用的資料。

最後,推薦Bruce Molay的《Understanding of Unix/Linux Programming》這本書,非常友好。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章