簡體   English   中英

如何使用C在Windows的創建過程函數中更改環境變量?

[英]How to Change Environment variable in the create process function in windows using C?

我編寫了這段代碼以根據用戶選擇啟動進程。 我想更改cmd shell的環境變量,以便在窗口中顯示“對我說話>”而不是“ C:\\ path>”,但也可以訪問cmd命令。 我知道我必須使用getenv()或putenv()函數設置一些值而不是NULL。 我為此寫了lib函數,但是我不知道如何在創建過程中代替Null來實現它。

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

// function prototype
void printError(char* functionName);

void lib(char* myFunction);
void lib(char* myFunction)
{
    char *lib;

   lib = getenv( "LIB" );
   if( lib != NULL )
      printf( "Original LIB variable is: %s\n", lib );
   _putenv( "LIB=speak to me>" );
   lib = getenv( "LIB" );
   if( lib != NULL )
      printf( " %s\n", lib );
}

int main()
{
   int i, choice;

   #define NUMBER_OF_PROCESSES 2
   LPTSTR lpCommandLine[NUMBER_OF_PROCESSES];
   PROCESS_INFORMATION processInfo[NUMBER_OF_PROCESSES];

   STARTUPINFO startInfo;
   ZeroMemory(&startInfo, sizeof(startInfo));
   startInfo.cb = sizeof(startInfo);
   startInfo.lpTitle = "What is your Command?";
   startInfo.dwFillAttribute = FOREGROUND_BLUE| BACKGROUND_RED| BACKGROUND_GREEN| BACKGROUND_BLUE| BACKGROUND_INTENSITY;
   startInfo.dwFlags = STARTF_USEFILLATTRIBUTE;

   /* set up the command lines */
   lpCommandLine[0] = "C:\\Windows\\notepad.exe";
   lpCommandLine[1] = "C:\\Windows\\system32\\cmd.exe";


   /* create the processes with user choice */   
  while(1)
  {
      printf("\n Please choose from the following list\n");
      printf("  0.Quit\n");
      printf("  1.Run Notepad\n");
      printf("  2.Run Cmd shell\n");
      printf(" enter number:");
      scanf("%d",&choice);
      switch(choice)
      {

      case 1:
        if( !CreateProcess(NULL, lpCommandLine[0], NULL, NULL, FALSE,
                         HIGH_PRIORITY_CLASS | CREATE_NEW_CONSOLE,
                         NULL, NULL, &startInfo, &processInfo[0]) )
      {
          printError("CreateProcess");
      }
      else
      {
         printf("Started program %d with pid = %d\n\n",1 , (int)processInfo[0].dwProcessId);
      }
      break;
      case 2:
        if( !CreateProcess(NULL, lpCommandLine[1], NULL, NULL, FALSE,
                         HIGH_PRIORITY_CLASS | CREATE_NEW_CONSOLE,
                         NULL, NULL, &startInfo, &processInfo[1]) )
      {
          printError("CreateProcess");
      }
      else
      {
         printf("Started program %d with pid = %d\n\n",2 , (int)processInfo[1].dwProcessId);
      }
      break;
      case 0:
        exit(0);
      break;
      default: printf("wrong choice");
               break;
      }
  }

   /* close all the handles */
   for (i = 0; i < NUMBER_OF_PROCESSES; i++)
   {
      CloseHandle(processInfo[i].hThread);
      CloseHandle(processInfo[i].hProcess);
   }

   return 0;
}



/****************************************************************
   The following function can be used to print out "meaningfull"
   error messages. If you call a Win32 function and it returns
   with an error condition, then call this function right away and
   pass it a string containing the name of the Win32 function that
   failed. This function will print out a reasonable text message
   explaining the error and then (if chosen) terminate the program.
*/
void printError(char* functionName)
{
   LPVOID lpMsgBuf;
    int error_no;
    error_no = GetLastError();
    FormatMessage(
         FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
         NULL,
         error_no,
         MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
         (LPTSTR) &lpMsgBuf,
         0,
         NULL
    );
    // Display the string.
    fprintf(stderr, "\n%s failed on error %d: ", functionName, error_no);
    fprintf(stderr, (const char*)lpMsgBuf);
    // Free the buffer.
    LocalFree( lpMsgBuf );
    //ExitProcess(1);  // terminate the program
}//printError

如果願意,可以將PROMPT環境變量設置為默認$p$g以外的其他值。 這是它的用法:

PROMPT [text]

  text    Specifies a new command prompt.

Prompt can be made up of normal characters and the following special codes:

  $A   & (Ampersand)
  $B   | (pipe)
  $C   ( (Left parenthesis)
  $D   Current date
  $E   Escape code (ASCII code 27)
  $F   ) (Right parenthesis)
  $G   > (greater-than sign)
  $H   Backspace (erases previous character)
  $L   < (less-than sign)
  $N   Current drive
  $P   Current drive and path
  $Q   = (equal sign)
  $S     (space)
  $T   Current time
  $V   Windows version number
  $_   Carriage return and linefeed
  $$   $ (dollar sign)

要在對CreateProcess的調用中傳遞此變量,可以使用lpEnvironment參數:

    CreateProcess(NULL, lpCommandLine[1], NULL, NULL, TRUE,
            HIGH_PRIORITY_CLASS | CREATE_NEW_CONSOLE,
            (LPVOID) _T("PROMPT=speak to me$g\0\0"), NULL, &startInfo, &processInfo[1]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM