Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hey guys i have written a code to retrive a task schedular information which displays the names of tasks and its states. the code works well. but the problem i am facing now is in windows server 2003 i found that my code is not running as ITaskService cannot be instantiated or it is not recognisable. hence forth i have written another code. what it does is it retrives the list of all task inside
C:\WINDOWS\Tasks

but now i want to print its states as well which is not getting displayed through my code. how must i retrive it?

here my code :

C++
#include "stdafx.h"
#include <windows.h>
#include <tchar.h>
#include <windows.h>
#include <windows.h>
#pragma warning (disable : 4996)
#include "dirent.h"
int main()
{

	DIR *dirp;
	struct dirent *ent;
	if ((dirp = opendir("C:\\WINDOWS\\Tasks")) != NULL) {
		/* print all the files and directories within directory */
		while ((ent = readdir(dirp)) != NULL) {
			printf("%s\n", ent->d_name);
		}
		closedir(dirp);
	}
	else {
		/* could not open directory */
		perror("");
		return EXIT_FAILURE;
	}
}

along with this i also want to put the condition that for win server 2003 the above code should run where as for other OS's the following code must run:


C++
TASK_STATE taskState;
void Taskschedular()
{
	
	try
	{
		

		//USES_CONVERSION;
		//------------------------------task-------------------------------------------------------------------------
		HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
		if (FAILED(hr))
		{
			printf("\nCoInitializeEx failed: %x", hr);
			outputFile << "\nCoInitializeEx failed: %x" << hr;

		}

		//  Set general COM security levels.
		hr = CoInitializeSecurity(
			NULL,
			-1,
			NULL,
			NULL,
			RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
			RPC_C_IMP_LEVEL_IMPERSONATE,
			NULL,
			0,
			NULL);

		if (FAILED(hr))
		{
			printf("\nCoInitializeSecurity failed: %x", hr);
			outputFile << "\nCoInitializeSecurity failed" << hr;
			CoUninitialize();

		}

		//  ------------------------------------------------------
		//  Create an instance of the Task Service. 
		ITaskService *pService = NULL;
		hr = CoCreateInstance(CLSID_TaskScheduler,
			NULL,
			CLSCTX_INPROC_SERVER,
			IID_ITaskService,
			(void**)&pService);
		if (FAILED(hr))
		{
			printf("Failed to CoCreate an instance of the TaskService class: %x", hr);
			CoUninitialize();
			outputFile << "Failed to CoCreate an instance of the TaskService class: %x" << hr;

		}

		//  Connect to the task service.
		hr = pService->Connect(_variant_t(), _variant_t(),
			_variant_t(), _variant_t());
		if (FAILED(hr))
		{
			printf("ITaskService::Connect failed: %x", hr);
			outputFile << "ITaskService::Connect failed: %x" << hr;
			pService->Release();
			CoUninitialize();

		}

		//  ------------------------------------------------------
		//  Get the pointer to the root task folder.
		ITaskFolder *pRootFolder = NULL;
		hr = pService->GetFolder(_bstr_t(L"\\"), &pRootFolder);

		pService->Release();
		if (FAILED(hr))
		{
			printf("Cannot get Root Folder pointer: %x", hr);
			CoUninitialize();
			outputFile << "Cannot get Root Folder pointer: %x" << hr;

		}

		//  -------------------------------------------------------
		//  Get the registered tasks in the folder.
		IRegisteredTaskCollection* pTaskCollection = NULL;
		hr = pRootFolder->GetTasks(NULL, &pTaskCollection);

		pRootFolder->Release();
		if (FAILED(hr))
		{
			printf("Cannot get the registered tasks.: %x", hr);
			CoUninitialize();
			outputFile << "Cannot get the registered tasks.: %x" << hr;

		}

		LONG numTasks = 0;
		hr = pTaskCollection->get_Count(&numTasks);

		if (numTasks == 0)
		{
			//printf("\nNo Tasks are currently running");
			pTaskCollection->Release();
			CoUninitialize();

		}

		//printf("\nNumber of Tasks : %d", numTasks);
		//cout << "Task Names:";
		outputFile << "Task Names and Status:\n\n";

		//outputFile.close();
		//TASK_STATE taskState;
		//USES_CONVERSIONS;

		int t = 0;
		for (LONG i = 0; i < numTasks; i++)
		{
			IRegisteredTask* pRegisteredTask = NULL;
			hr = pTaskCollection->get_Item(_variant_t(i + 1), &pRegisteredTask);

			if (SUCCEEDED(hr))
			{
				BSTR taskName = NULL;
				hr = pRegisteredTask->get_Name(&taskName);
				if (SUCCEEDED(hr))
				{
					//		printf("\t \n %S", taskName);
					//objLog.WriteToLog("MSG","Tasks",taskName);
					char	TaskLog[512] = { 0 };
					//char	taskstatesLog[512] = { 0 };
					sprintf(TaskLog, "\t  %S", taskName);
					x_task.push_back(string(CW2A(taskName)));


					//strcpy(x_task, TaskLog);
					/*x_task += TaskLog;
					x_task += " ";*/
					SysFreeString(taskName);
					objLog.WriteToLog("INFO", "Task", TaskLog);

					/*std::wstring tmpString(taskName);

					std::string str(tmpString.begin(), tmpString.end());
					outputFile << str.c_str();
					outputFile << std::endl;*/

					hr = pRegisteredTask->get_State(&taskState);
					if (SUCCEEDED(hr))

						printf("", taskState);


					std::wstring tmpString(taskName);

					std::string str(tmpString.begin(), tmpString.end());
					outputFile << str.c_str();

					//	outputFile << std::endl;
					STATE job_state = Queued;

				//	outputFile << "%s" << job_state << 1 ? "Disabled" : job_state == 2 ? "Queued" : job_state == 3 ? "Ready" : "Running";
					if (taskState == 1)
					{

						//	printf(": disable \n");
						outputFile << "\t :disable \n";
						objLog.WriteToLog("", "", "\t : disable");

					}

					else	if (taskState == 2)
					{

						//printf(": queued \n ");
						outputFile << "\t :queued \n";
						objLog.WriteToLog("", "", "\t : queued");
					}

					else	if (taskState == 3)
					{

						//printf(": ready\n");

							outputFile << "\t :ready \n";
						objLog.WriteToLog("", "", "\t : ready");
					}

					else if (taskState == 4)
					{

						//printf(": running \n ");
						outputFile << "\t :running \n";
						objLog.WriteToLog("", "", "\t : running");
					}

					else
						printf("\n\tCannot get the registered task state: %x", hr);

				}
				else
				{
					printf("\nCannot get the registered task name: %x", hr);

				}
				pRegisteredTask->Release();
			}
			else
			{
				printf("\nCannot get the registered task item at index=%d: %x", i + 1, hr);

			}

		}
		outputFile << "\n---------------------------------------------------\n";
		pTaskCollection->Release();
		CoUninitialize();

	}

	
	
	catch (exception e)
	{
		objLog.WriteToLog("error", "task schedular", "exception in tasks");
	}
}
Posted
Updated 7-Jun-15 22:20pm
v3

hi,
there is a way to detect the OS using #define and for windows version helper functions are also there.

check here[^]

For windows OS check here[^]

Operating System Version[^]

http://nadeausoftware.com/articles/2012/01/c_c_tip_how_use_compiler_predefined_macros_detect_operating_system[^]

hope this helps !!
 
Share this answer
 
v2
First of all (before others will tell you) do you know that support for Win Server 2003 will end on july 2015? Have you considered to migrate to a new system? Why so much effort for a system that is dead? ... etc...
Ok now let's look in more general view your question: "How to tailor code for different OS's". In C the most common way is to include the specifica parts of the code in conditional compilation using the #if/#else/#endif operators:
C++
#ifdef CODETHIS
   ...    //Some code
 #else
   ...    //some other code
 #endif

This can be almost automatic using special predefined symbols that come from compiler. I.e. the following code makes a conditional compilation depending if we are using linux or windows:
C++
#ifdef _WIN32
   ...    //code specific for WINDOWS
 #elif defined(linux)
   ...    //Code specific for linux
 #else
 #pragma error("Unknown OS!")
 #endif


To make distinction between windows versions you have to use NTDDI_VERSION and WIN32_WINNT. For their values see[^] this link.
In your case you can set the value of the 2 from compiler command line (using option /D) and adjust your code conseguently:
C++
#if (_WIN32_WINNT == _WIN32_WINNT_WS03) /*Windows Server 2003 with SP1, Windows XP with SP2*/ || (_WIN32_WINNT == _WIN32_WINNT_XP) /*Windows Server 2003, Windows XP*/
   ...    //code specific for WINDOWS SERVER 2003
 #else
   ...    //Code for other systems
 #endif


One more important note use only the preprocessor and preprocessor symbols, don't use any function to check the OS type. In the first case the code not required is simply omitted (not compiled at all), in the second case a function requires that the code executes to get an answer. This means that the compiler will compile the whole code as a standard if/else. It will be very probable then that the functions for the different OS will not be available in one or another code you'll never be able to compile your code (even the dead code optimization couldn't work with function results).
 
Share this answer
 
v5
Comments
Member 11460314 8-Jun-15 5:23am    
hey i am trying it usng my code but its not recognizing the OS. is it something like this to write?
#if (_WIN32_WINNT == _WIN32_WINNT_WS03) /*Windows Server 2003 with SP1, Windows XP with SP2*/ || (_WIN32_WINNT == _WIN32_WINNT_XP) /*Windows Server 2003, Windows XP*/
printf("hi"); //code specific for WINDOWS SERVER 2003
#else
printf("hello"); //Code for other systems
#endif

i tried this code on different os's but it prints hello (especially on win serveer 2003 it prints hello instead hi)
Frankie-C 8-Jun-15 6:29am    
I already explained above that while the symbol _WIN32 is automatically defined by the compiler the values of _WIN32_WINNT and WINVER are not.
You have to manually set them (please see https://msdn.microsoft.com/en-us/library/windows/desktop/aa383745%28v=vs.85%29.aspx#setting_winver_or__win32_winnt).
Read carefully the links provided.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900