tsg21 2016大容规:linux execlp

来源:百度文库 编辑:偶看新闻 时间:2024/04/29 08:49:21

//实现从命令行输入命令,然后执行

//#include#include#include#define MAX_LINE 1024int main(){char buf[ MAX_LINE ] ;pid_t pid ;int status ;printf( "%%" ) ;// printf prompt % need %%while( fgets( buf , MAX_LINE , stdin ) != NULL ){buf[ strlen( buf ) - 1 ] = 0 ;if( ( pid = fork() ) < 0 ){printf( " fork error.\n" ) ;}else if( pid == 0 ){ // 子进程// 执行程序execlp( buf , buf , ( char * ) 0) ; // 执行程序printf( "%s" , buf ) ;return 1 ;}// parent 进程,等待子进程进程结束if( ( pid = waitpid( pid , &status , 0 ) ) < 0 ){printf( "waitpid error.\n" ) ;}printf( "%%" ) ;}return 0 ;