Wait until all background jobs have terminated, C - process

I know how waitpid(-1...) allows me to wait until all children have finished, such as waitpid(-1, &status). But how can I wait until all background processes are finished? Someone suggested that I can use the same waitpid (in a loop?) to achieve this but I don't see how.
To be clear, I'm implementing a shell, and need to add a new built-in command wait, which waits until all background jobs have terminated before returning to the prompt.
I read somewhere else on SO that "You will also want to call waitpid() with the WNOHANG option regularly - say, immediately before you display the shell prompt. This will allow you to detect when the background process has exited or stopped " But again, child != background. So even that I don't believe.
Edit:
I ended up just doing while(wait(NULL) > 0); and that's it, it worked. But what I'm still confused about is don't I WANT to make a distinction between foreground and background because the wait I'm implementing only waits for the background processes, and all children are equal in the eye of wait() or waitpid().
So again, the children I'm waiting for by using wait() or waitpid() aren't necessarily background processes. Am I wrong?

Since you ask in the context of implementing a shell, and evidently your shell supports enough job control to have a concept of background processes, it is reasonable to suppose that your implementation will have a table in which it tracks background jobs. That table can and should track the PID of the process associated with each job.
Having those PIDs in hand, you can waitpid() for specific background jobs until there are no more in the table, or you can waitpid(-1) to collect
any and every job, in a loop, until there are no more background jobs in the table.

If you want to implement background process (and job control) and catch their termination (at least) you must set a signal handler for SIGCHLD, and call wait(-1) inside it. This will let your shell receive asynchronous notifications of background processes termination. You may have a look at Catching SIGCHLD for example and discussion about this.

Related

when I quit my application, how to ensure ongoing threads are not interrupted at a bad moment?

I'm new to threading, so there are a few things I'm trying to grasp correctly.
I have a windows form application that uses threading to keep my UI responsive while some server shenanigans are going on.
My question is: when I quit my application, what happens to ongoing threads? Will they run to completion or will the abruptly be interrupted?
If they are interrupted, what can I do to make sure they at least don't get interrupted in such a way that would corrupt data on my server (force them to run to a safe place in the code where I know it's ok to interrupt the execution)
You will want to keep a reference of said threads, and call .Abort() on them when you want to terminate. Then you put your thread's code in a try/catch block and handle ThreadAbortException's. This will let you clean up what you are doing and terminate the thread cleanly at your own pace. In the main thread, after you called .Abort(), you just wait until the thread is no longer running (by polling the .IsAlive property of the Thread object) and close your application afterwards.
A thread needs a process to run in. The process won't be able to terminate if you don't terminate all the non-background threads you have started. Threads marked as background thread will be aborted.
So, the behavior is entirely up to your implementation. If you want to close the application, you could wait for all threads to terminate by themself, you could set an event to ask them to terminate and wait or you could just kill the threads.
The UI thread will terminate by itself because it runs a messageloop that stops when requested by the operating system, also see wikipedia and this answer.

how to show msgbox if any process is closed

This is my code, it works only on form load or click.
But I need to show this msgbox when process close while my app running.
Dim p() As Process
p = Process.GetProcessesByName("notepad")
If p.Count > 0 Then
' Process is running
MsgBox("Running!")
Else
' Process is not running
MsgBox("Not running!")
End If
So, you want to monitor the status->Running or status->NotRunning of a process,
while your Application is executing.
This requires a method that continuously updates the Status of a monitored foreign process.
How this method works, depends on you application functionality:
Is invisible and becomes visible/operable when the monitored process
starts?
Operates indipendently from this foreign process, but takes special
actions when this other process becomes active?
Executes visible and its only purpose is to monitor the foreign
process?
Other
First take a look to:
Check if process is done in VB.Net
application closes itself when another program closes?
Wait for a specefic program to open before continue VB.NET
I suggest you learn how to instantiate a BackgroundWorker.
It's a very straightforward and helpful tool to use if you don't want to manually control an Asynchronous task.
A BackgroundWorker can be instructed to notify your main process (application) that a defined condition has changed.
When this condition is met, the BW raises an Event, letting you know what happend or changed.
Then you decide how to proceed, or - if it is the case - you can terminate the activity of the BackgroundWorker.
Give it a try.

GPUImage gpus_ReturnNotPermittedKillClient crash using GPUImageFilter

I'm using GPUImageFilter in a chain, and most of the time it works OK. I've recently come across a few random crashes that match the symptoms in this github issue (albeit I'm using GPUImageFilter not live capture or video). I'm trying to find a suitable method that can ensure I've cleared the frame buffer and any other GPUImage-related activities in willResignActive.
Currently I have:
[[GPUImageContext sharedFramebufferCache] purgeAllUnassignedFramebuffers];
Is this sufficient? Should I use something else instead/in addition to?
As indicated there, seeing gpus_ReturnNotPermittedKillClient in a stack trace almost always is due to OpenGL ES operations being performed while your application is in the background or is just about to go to the background.
To deal with this, you need to guarantee that all GPUImage-related work is finished before your application heads to the background. You'll want to listen for delegate notifications that your application is heading to the background, and make sure all processing is complete before that delegate callback exits. The suggestion there by henryl is one way to ensure this. Add the following near the end of your delegate callback:
runSynchronouslyOnVideoProcessingQueue(^{
// Do some operation
});
What that will do is inject a synchronous block into the video processing pipeline (which runs on a background queue). Your delegate callback will block the main thread at that point until this block has a chance to execute, guaranteeing that all processing blocks before it have finished. That will make sure all pending operations are done (assuming you don't add new ones) before your application heads to the background.
There is a slight chance of this introducing a deadlock in your application, but I don't think any of my code in the processing pipeline calls back into the main queue. You might want to watch out for that, because if I do still have something in there that does that, this will lock your application. That internal code would need to be fixed if so.

dispatch_async vs beginBackgroundTaskWithExpirationHandler

I need to implement a background process in an iOS app, that performs a job every 60 seconds. I know this can only be done while the app is in focus, but I do want this job to finish running in the background after the app is closed. I will use GCD to dispatch a timer that calls my job asynchronously every 60 seconds using either dispatch_async or beginBackgroundTaskWithExpirationHandler.
I am wondering which method is the best, or if they are essentially the same. Is it okay to use beginBackgroundTaskWithExpirationHandler to execute a job even while the app is in the foreground? Or am I better off trying to cancel the job when the app state changes, and then restart the job as a background task?
-beginBackgroundTaskWithExpirationHandler: doesn't run code on a background thread/queue. It tells the OS that you are going to continue doing work when your app is not active.
The two serve completely different purposes.

Make Thread sleep first before it runs

How can I make my thread sleep first before it runs? I know how to get sleep to work, however, whenever my program is run, the thread immediately runs. I want it to WAIT once it is first created to start running. (I am using handlers)
You cannot control when threads are scheduled. If you want it to go to sleep, have the first statement in the thread subroutine do a wait on a condition or something like that and when you are ready you can broadcast to that condition. In pseudo-code:
get-lock
if (we-are-still-supposed-to-sleep)
pthread_cond_wait()
release-lock
I suppose you could have the parent hold the lock while creating the children and then all they have to do is:
get-lock
release-lock
and avoid the condition thing.
What OS? Windoze allows you to create threads in a suspended state. When you have loaded up the thread fields in the ctor, you can resume the thread. Failing that, pass some synchro object in the thread start parameter for the new thread to wait on.
Rgds,
Martin.