Thread: Can not use popen()

  1. #16
    Registered User
    Join Date
    Oct 2007
    Posts
    12
    Quote Originally Posted by brewbuck View Post
    Sure, but Windows has _popen(), others have popen(), so why not use it. If you use execvp() you have to deal with forking a new process, creating the pipes, reaping the process, etc, all of which popen() takes care of for you.
    Yes, I used popen(). But there is problem, i don't know why ?

    I create new project use Microsoft VC++, create class Example.c

    Code:
    #include <stdlib.h>
    #include <stdio.h>
    main(){
    
    	    FILE *fp;	   
    	   char line[200];
    	   fp = _popen("java -version 2>&1","r"); 
    		if(fp == NULL) {	
    			exit(1);
    		}
    		while(!feof(fp)) {
    		   if(fgets(line, sizeof line, fp)) {			   
    			printf("%s", line);
    			  
    		   }
    			
    		}
    		_pclose(fp);
    }
    this code run very well

    But I copy this part:
    Code:
               FILE *fp;	   
    	   char line[200];
    	   fp = _popen("java -version 2>&1","r"); 
    		if(fp == NULL) {	
    			exit(1);
    		}
    		while(!feof(fp)) {
    		   if(fgets(line, sizeof line, fp)) {			   
    			printf("%s", line);
    			  
    		   }
    			
    		}
    		_pclose(fp);
    paste in to main() method of other project, when run, fp have not result and call exit()

    I compile have not error. I don't know why ? I work on Windows environment

  2. #17
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > while(!feof(fp))
    You had the right code in your first post, why have you now broken it?
    See the FAQ for why feof() is bad usage in a loop control.

    > paste in to main() method of other project, when run, fp have not result and call exit()
    Perhaps something messed with the PATH, and 'java' no longer found.
    Does _popen() also set errno to indicate why it could not run the requested program?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #18
    Registered User
    Join Date
    Oct 2007
    Posts
    12
    Quote Originally Posted by Salem View Post
    > while(!feof(fp))
    You had the right code in your first post, why have you now broken it?
    See the FAQ for why feof() is bad usage in a loop control.

    > paste in to main() method of other project, when run, fp have not result and call exit()
    Perhaps something messed with the PATH, and 'java' no longer found.
    Does _popen() also set errno to indicate why it could not run the requested program?
    let me correct code after, thanks many

    I found root cause.

    If I set "Set Active Configuration" to Debug in menu Build, this case do not error. fp # null,
    If I set "Set Active Configuration" to Release in menu Build, this case error, fp = null

    Please help

  4. #19
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    What other changes do you make in debug vs release build? There is probably something else that changes, which causes it to go wrong - I doubt very much that the real problem is in _popen() or the code generation.

    Any warnings in the build? Perhaps set warning level to 4?

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  5. #20
    Registered User
    Join Date
    Oct 2007
    Posts
    12
    Quote Originally Posted by matsp View Post
    What other changes do you make in debug vs release build? There is probably something else that changes, which causes it to go wrong - I doubt very much that the real problem is in _popen() or the code generation.

    Any warnings in the build? Perhaps set warning level to 4?

    --
    Mats
    Checked, do not warning or error when compile

    but make in debug mode fp # null
    make in release mode fp always = null

    below is all my example

    Code:
    #include <stdio.h>
    
    FILE *fp;	   
    char line[200];
    char javaVersion[200];
    
    void checkJavaVersion();
    main()
    {	   
    	 checkJavaVersion();
    		
    }
    
    void checkJavaVersion(){
    
    	fp = _popen("java -version 2>&1","r"); 
    	if(fp == NULL) {			
    		printf("Cannot open file.\n");
    		exit(1);
    	}
    	while(fgets(line, sizeof line, fp)) {		   			   	
    		strcat(javaVersion, line);		   			
    	}
    	printf("output %s", javaVersion);
    	if(strstr(javaVersion, "IBM") != (char) NULL){				
    			printf("This jre is IBM !!!!");	
    	}
    	_pclose(fp);
    
    }
    and this is "Object/Library module"

    kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib

  6. #21
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    All other things being equal, the only difference between debug and release is the current directory when you run the code.

    Is there perhaps a 'java' in your debug directory and not in the release directory?

    For further debug, try adding
    Code:
    {
      char here[1000] = { 0 };
      char *p = getenv("PATH");
      printf( "Path=%s\n", p ? p : "Not set" );
      _getcwd( here, sizeof here ); /* manual */
      printf( "Here=%s\n", here );
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  7. #22
    Registered User
    Join Date
    Oct 2007
    Posts
    12
    Quote Originally Posted by Salem View Post
    All other things being equal, the only difference between debug and release is the current directory when you run the code.

    Is there perhaps a 'java' in your debug directory and not in the release directory?

    For further debug, try adding
    Code:
    {
      char here[1000] = { 0 };
      char *p = getenv("PATH");
      printf( "Path=%s\n", p ? p : "Not set" );
      _getcwd( here, sizeof here ); /* manual */
      printf( "Here=%s\n", here );
    }
    I tried your code and run well, get all PATH and my project location

    I recognised that when i create my project with "Win32 Console Application" very thing as good, fp = _popen("java -version 2>&1", "r"); work well

    but if I create my project with "Win32 Application", as this case, fp = _popen("java -version 2>&1", "r"); can not work, fp always = null

    Why ? or I miss library ?. How I configuration on mode"Win32 Application" to fp = _popen("java -version 2>&1", "r"); can work as mode "Win32 Console Applicaion"

    one again, please help me

    many thanks

  8. #23
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    The manual page for _popen reads
    Quote Originally Posted by msdn
    Note If used in a Windows program, the _popen function returns an invalid file pointer that will cause the program to hang indefinitely. _popen works properly in a Console application. To create a Windows application that redirects input and output, see Creating a Child Process with Redirected Input and Output in the Platform SDK.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  9. #24
    Registered User
    Join Date
    Oct 2007
    Posts
    12
    Quote Originally Posted by Salem View Post
    Many thanks you all helped me on this thread
    Everything seem that is difficulty

    Let me describe again
    Assume you create new Win32 Application project with select "a typical Hello Word ! application ". When you execute this project, system will show a window contain "Hello Word !" string.

    I expect to replace string "Hello Word!" with value of cammand "netstat -n"

    Example: replace "Hello Word !" with
    "Proto Local Address Foreign Address State
    TCP 127.0.0.1:1148 127.0.0.1:1149 ESTABLISHED
    TCP 127.0.0.1:1149 127.0.0.1:1148 ESTABLISHED
    TCP 127.0.0.1:1150 127.0.0.1:1151 ESTABLISHED"

    many thanks

  10. #25
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    And did you goto the MSDN link I posted, and then followed the "Creating a Child Process with Redirected Input and Output" link for how to do this in a Win32 GUI program?

    We're not here to do all the work for you.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  11. #26
    Registered User
    Join Date
    Oct 2007
    Posts
    12
    Quote Originally Posted by Salem View Post
    And did you goto the MSDN link I posted, and then followed the "Creating a Child Process with Redirected Input and Output" link for how to do this in a Win32 GUI program?

    We're not here to do all the work for you.
    I created project Win32 Application and use this is function that help me to archive my goal

    Code:
    DWORD RunSilent(char* strFunct, char* strstrParams)
    {
    	STARTUPINFO StartupInfo;
    	PROCESS_INFORMATION ProcessInfo;
    	char Args[4096];
    	char *pEnvCMD = NULL;
    	char *pDefaultCMD = "CMD.EXE";
    	ULONG rc;
    	
    	memset(&StartupInfo, 0, sizeof(StartupInfo));
    	StartupInfo.cb = sizeof(STARTUPINFO);
    	StartupInfo.dwFlags = STARTF_USESHOWWINDOW;
    	StartupInfo.wShowWindow = SW_HIDE;
    
    	Args[0] = 0;
    
    	pEnvCMD = getenv("COMSPEC");
    
    	if(pEnvCMD){
    		
    		strcpy(Args, pEnvCMD);
    	}
    	else{
    		strcpy(Args, pDefaultCMD);
    	}
    
    	// "/c" option - Do the command then terminate the command window
    	strcat(Args, " /c "); 
    	//the application you would like to run from the command window
    	strcat(Args, strFunct);  
    	strcat(Args, " "); 
    	//the parameters passed to the application being run from the command window.
    	strcat(Args, strstrParams); 
    	
    	if (!CreateProcess( NULL, Args, NULL, NULL, FALSE,
    		CREATE_NEW_CONSOLE, 
    		NULL, 
    		NULL,
    		&StartupInfo,
    		&ProcessInfo))
    	{
    	
    
    		return GetLastError();		
    	}
    
    	WaitForSingleObject(ProcessInfo.hProcess, INFINITE);
    	if(!GetExitCodeProcess(ProcessInfo.hProcess, &rc))
    		rc = 0;
    
    	CloseHandle(ProcessInfo.hThread);
    	CloseHandle(ProcessInfo.hProcess);
    
    	return rc;
    	
    }
    I run this function with argument:
    RunSilent("java -version","2>> javaVersion.txt");

    many thanks you all helped me more

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. popen and fgets, underflow!
    By henrikstolpe in forum Linux Programming
    Replies: 0
    Last Post: 02-06-2009, 03:39 AM
  2. popen takes too long?
    By Largo in forum C Programming
    Replies: 2
    Last Post: 11-20-2006, 06:46 AM
  3. popen()
    By Cactus_Hugger in forum Windows Programming
    Replies: 2
    Last Post: 10-22-2005, 03:16 PM
  4. popen vs fopen
    By esme in forum Linux Programming
    Replies: 1
    Last Post: 11-25-2002, 10:37 AM