popen/pclose 的阻塞问题
pclose()
功能:关闭到一个进程的管道.
语法:#include <stdio.h>
int pclose(strm)
FILE *strm;
说明:本系统调用用于关闭由popen()打开的管道,并会等待由popen()
激活的命令执行结束后,关闭管道后读取命令返回码.
返回值:若关闭的文件描述符不是由popen()打开的,则返回-1.
=====================================================================
根据以上描述,我认为:pclose相当于一个阻塞,如果popen打开的命令行不完成并返回,那么pclose应该保持阻塞。
一下是我的测试代码:
/////////////////////////////////////////////
//g++ test.cpp -o test
#include <iostream>
using namespace std;
int main()
{
cout<<"[4--popen]sleeping in the popen..."<<endl;
sleep(30);
return 0;
}//end test.cpp
////////////////////////////////////////
//g++ main.cpp -lpthread -o main
#include <pthread.h>
#include <errno.h>
#include <iostream>
using namespace std;
pthread_t pht;
int phi;
void* pthreadproc( void* arg )
{
FILE* fp;
int num;
int pc;
cout<<"[2--thread]popen begin!!"<<endl;
fp = popen( "./test", "r" );
cout<<"[3--thread]waiting for popen return and pclose...."<<endl;
pc = pclose( fp );
cout<<"[5--thread]pclosed:%d"<<pc<<"ERROR"<<strerror(errno)<<endl;
}
int main()
{
for( int i = 0; i<1000; i++ )
{
cout<<"[1--main]thread begin"<<endl;
phi = pthread_create( &pht, NULL, pthreadproc, NULL );
if ( phi != 0 )
{
cout<<"[2--main]thread create failed!ERROR CODE:%s"
<<strerror(errno)
<<endl;
}
cout<<"[2--main]waiting for thread return......."<<endl;
phi = pthread_join( pht, NULL );
if ( phi != 0 )
{
cout<<"[6--main]thread create failed!ERROR CODE:%s"
<<strerror(errno)
<<endl;
}
else
cout<<"[6--main]thread returned"<<endl;
}
}//end main.cpp
期望的输出结果:1->2->2->3....waiting30s....->5->6
但是实际测试结果中:123456的顺序是不变,但是中间的30秒等待就不一定,证明pclose没有等待popen打开的test返回就放弃阻塞让线程返回了?
那位高手给点拨点拨呀,郁闷ing....