Allow only one running instance of a program - objective-c

How can i restrict my program to run only instance? Currently i'm running my program as daemon(starts and stops automatically), and when user clicks and tries to launch again(which is not a valid usecase), process gets launched in user context and i would like to avoid this for many reasons.
How can i achieve this?
As of now i'm getting list of processes and doing some checks and exiting at the begining itself but this method is not clean, though it solves my problem.
can someone give me a better solution?
And i'm using ps to get process list, is there any reliable API to get this done?

Use a named semaphore with count of 1. On startup, check if this semaphore is taken. If it is, quit. Otherwise, take it.
Proof of concept code: (put somewhere near application entry point)
#include <semaphore.h>
...
if (sem_open(<UUID string for my app>, O_CREAT, 600, 1) == SEM_FAILED) {
exit(0);
}
From the sem_open documentation,
The returned semaphore descriptor is available to the calling process until it is closed with sem_close(), or until the caller exits or execs.

Related

Ensure a web server's query will complete even if the client browser page is closed

I am trying to write a control panel to
Inform about certain KPIS
Enable the user to init certain requests / jobs by pressing a button that then runs a stored proc on the DB or sets a specific setting etc
So far, so good, except I would like to run some bigger jobs where the length of time that the job is running for is unknown and could run over both the script timeout period AND the time the user is willing to wait for a response.
What I want is a "fire and forget" process so the user hits the button and even if they kill the page or turn off their phone they know the job has been initiated and WILL complete.
I was looking into C# BeginExecuteNonQuery which is an async call to the query so the proc is fired but the control doesn't have to wait for a response from it to carry on. However I don't know what happens when the page/app that fired it is shut.
Also I was thinking of some sort of Ajax command that fires the code in a page behind the scenes so the user doesn't know about it running but then again I believe if the user shuts the page down the script will die and the command will die on the server as well.
The only way for certain I know of is a "queue" table where jobs are inserted into this table then an MS Agent job comes along every minute or two checking for new inserts and then runs the code if there is any. That way it is all on the DB and only a DB crash will destroy it. It won't help with multiple jobs waiting to be run concurrently that both take a long time but it's the only thing I can be sure of that will ensure the code is run at all.
Any ideas?
Any language is okay.
Since web browsers are unconnected, requests from them always take the full amount of time. The governing factor isn't what the browser does, but how long the web site itself will allow an action to continue.
IIS (and in general, web servers) have a timeout period for requests, where if the work being done takes simply too long, the request is terminated. This would involve abruptly stopping whatever is taking so long, such as a database call, running code, and so on.
Simply making your long-running actions asynchronous may seem like a good idea, however I would recommend against that. The reason is that in ASP and ASP.Net, asynchronously-called code still consumes a thread in a way that blocks other legitimate request from getting through (in some cases you can end up consuming two threads!). This could have performance implications in non-obvious ways. It's better to just increase the timeout and allow the synchronously blocking task to complete. There's nothing special you have to do to make such a request complete fully, it will occur even if the sender closes his browser or turns off his phone immediately after (presuming the entire request was received).
If you're still concerned about making certain work finish, no matter what is going on with the web request, then it's probably better to create an out-of-process server/service that does the work and to which such tasks can be handed off. Your web site then invokes a method that, inside the service, starts its own async thread to do the work and then immediately returns. Perhaps it also returns a request ID, so that the web page can check on the status of the requested work later through other methods.
You may use asynchronous method and call the query from this method.
Your simple method can be changed in to a asynch method in the following manner.
Consider that you have a Test method to be called asynchronously -
Class AsynchDemo
{
public string TestMethod(out int threadId)
{
//call your query here
}
//create a asynch handler delegate:
public delegate string AsyncMethodCaller(out int threadId);
}
In your main program /or where you have to call the Test Method:
public static void Main()
{
// The asynchronous method puts the thread id here.
int threadId;
// Create an instance of the test class.
AsyncDemo ad = new AsyncDemo();
// Create the delegate.
AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);
// Initiate the asychronous call.
IAsyncResult result = caller.BeginInvoke(
out threadId, null, null);
// Call EndInvoke to wait for the asynchronous call to complete,
// and to retrieve the results.
string returnValue = caller.EndInvoke(out threadId, result);
Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".",
threadId, returnValue);
}
From my experience a Classic ASP or ASP.NET page will run until complete, even if the client disconnects, unless you have something in place for checking that the client is still connected and do something if they are not, or a timeout is reached.
However, it would probably be better practice to run these sorts of jobs as scheduled tasks.
On submitting your web page could record in a database that the task needs to be run and then when the scheduled task runs it checks for this and starts the job.
Many web hosts and/or web control panels allow you to create scheduled tasks that call a URL on schedule.
Alternately if you have direct access to the web server you could create a scheduled task on the server to call a URL on schedule.
Or, if ASP.NET, you can put some code in global.asax to run on a schedule. Be aware though, if your website is set to stop after a certain period of inactivity then this will not work unlesss there is frequent continuous activity.

Obj-C, how can I log to a file how long a method took in seconds?

I envisage I'll run into problems as i haven't done this before.
I'm thinking that I can either define a date at the start of the method or initialise a class.
Then at the end of the method, call the commit method, which will write the time taken about with some sort of code to determine where the measurement was made.
Since you're crashing before the app finishes launching, so no code is going to fix this. If TestFlightApp isn't working, any other code-based solutions are likely to have the same problem.
As #dasblinkenlight noted, NSLog timestamps, so that's a really easy first step. Then you need to get the logs.
If possible, have your user install and run the iPhone Configuration Utility. Have her connect her device and select it from the Devices list. Then select Console and "Save Console As..." She can then mail it to you.

Pausing a DLL export until triggered by an EXE

Does anyone have any ideas of how a DLL function can be made to wait for “input”, and how to call a specific instance of a DLL export?
I’m trying to convert a Windows service to a DLL. It contains a function that logs some boot-up information and then waits until told to quit. The logging functionality is worked out, but I need to figure out two issues.
After it performs its main functions, the export needs to sit there and wait (like the classic Press any key to continue…, but minus the interface)
I need a way of having an executable subsequently tell the paused instance that it’s time to exit
For the first problem, I considered going into a loop and waiting on some sort of trigger, but of course it should not go into a 100%-CPU cycle, so maybe WaitForSingleObject or perhaps waiting for a message (eg WM_APP).
For the second, I thought of some kind of inter-process communication, but hopefully not something as messy as shared-memory or semaphores (I used shared-mem, semaphores, signals, etc. in Unix in uni, but this is on Windows). Of course I need a way of accessing the specific instance of the called export.
You can use CreateEvent, SetEvent, and WaitForSingleObject. If the dll was loaded by the executable that needs to signal the event that is all that is required. If it is from separate executables it is only slightly more complicated. When you call CreateEvent, create a named Event. This named event can be accessed by multiple processes. If it needs to work across different users logged in, prefix the name with "Global\" and it will be the same event for all processes for all users.
//in dll
HANDLE eventHandle = CreateEvent( NULL, TRUE, FALSE, "Global\\My-Unique-Trigger-Event" );
//do stuff
WaitForSingleObject( eventHandle, INFINITE);
//exit
//in executable
HANDLE eventHandle = CreateEvent( NULL, TRUE, FALSE, "Global\\My-Unique-Trigger-Event" );
SetEvent( eventHandle );

Hooking TerminateProcess & Getting Info From The Handle It Supplies

If you want to stop a process from being terminated, one way is to hook into TerminateProcess (or NtTerminateProcess). If the process is terminating itself (because you closed its window, for example), the handle supplied to those functions is NULL, so you can find out what executable is being terminated using GetCurrentProcess() & GetModuleFileNameEx(). As GetCurrentProcess() returns a pseudo-handle, you can access it with no problems.
If one process is terminating another, though, the handle supplied is not NULL. It represents the process being terminated. The problem is, you can't get information about that process. You can simply return a code saying "access denied" instead of calling the original [Nt]TerminateProcess(), but that blanket stops all processes from terminating others - which is a bad idea.
The handle must represent something valid otherwise TerminateProcess wouldn't be able to do anything useful with it - but I can't even call GetProcessId() on it, I get ERROR_INVALID_HANDLE (or ERROR_ACCESS_DENIED). I've tried various methods I've collected from the help and from online, including gaining the debug privilege (success) and DuplicateHandle() (same error) and ZwQueryInformationProcess() to get the ID (STATUS_ACCESS_DENIED). I can't even enumerate processes because they return IDs, and I can't get the ID, and OpenProcess() always returns a fresh handle, so I can't compare handles.
I can only assume the handle has PROCESS_TERMINATE right and nothing else. I know that Vista and higher have protected processes due to Digital Rights Management, but I'm using ProcessExplorer as my guinea pig so it's definitely not a media application!
Does anyone know how else I might be able to get any kind of information about the process being terminated from this handle?
It's just an ordinary process handle. The question is, in which process is your hook function executing? If it's the calling process, the handle can be used as-is for GetProcessId or NtQueryInformationProcess. If not, you need to call DuplicateHandle to duplicate the handle into your process.
If you're getting access denied errors, it may be because the process handle only has PROCESS_TERMINATE access. In that case, use DuplicateHandle to "re-open" the process with PROCESS_QUERY_(LIMITED_)INFORMATION access.

DuplicateHandle, why duplicate instead of just acquire?

Why would a process want to call DuplicateHandle from the Win32API, and get it from another process instead of just acquiring the handle on some object itself?
Is there some advantage to calling DuplicateHandle or something?
You may find the answer in Chapter 6.8 of 'Programming Applications for Microsoft Windows'.
Gaining a Sense of One's Own Identity
Sometimes you might need to acquire a real handle to a thread instead of a pseudo-handle. By "real," I mean a handle that unambiguously identifies a unique thread. Examine the following code:
DWORD WINAPI ParentThread(PVOID pvParam) {
HANDLE hThreadParent = GetCurrentThread();
CreateThread(NULL, 0, ChildThread, (PVOID) hThreadParent, 0, NULL);
// Function continues...
}
DWORD WINAPI ChildThread(PVOID pvParam) {
HANDLE hThreadParent = (HANDLE) pvParam;
FILETIME ftCreationTime, ftExitTime, ftKernelTime, ftUserTime;
GetThreadTimes(hThreadParent,
&ftCreationTime, &ftExitTime, &ftKernelTime, &ftUserTime);
// Function continues...
}
Can you see the problem with this code fragment? The idea is to have the parent thread pass to the child thread a thread handle that identifies the parent thread. However, the parent thread passes a pseudo-handle, not a real handle. When the child thread begins executing, it passes the pseudo-handle to the GetThreadTimes function, which causes the child thread to get its own CPU times, not the parent thread's CPU times. This happens because a thread pseudo-handle is a handle to the current thread— that is, a handle to whichever thread is making the function call.
To fix this code, we must turn the pseudo-handle into a real handle. The DuplicateHandle function (discussed in Chapter 3) can do this transformation
One possible use of DuplicateHandle is to duplicate a handle between a 32-bit process and a 64-bit process.
Note: cannot be used on I/O Completion ports or Sockets.
Another use of DuplicateHandle is to open a file in multiple processes when the file uses FileOptions.DeleteOnClose. (such a file cannot be opened by multiple processes if the file path is used to open the file)
See my answer at https://stackoverflow.com/a/36606283/2221472
See here on the MSDN what it has to say about the usage of 'DuplicateHandle'. The best way I can think of it is this way, an analogy if you like - suppose you open a file using the CreateHandle routine for writing only, then you call DuplicateHandle to pass the handle onto another thread in which the thread will read from the file, only the handle is duplicated hence the thread does not have to call CreateHandle again...