How to kill process completely from a thread in Linux (C) - c

I have a C code that runs on Linux that creates a certain amount of threads. In one of the threads, I want it so that if it runs into a certain condition, it should terminate the entire process. I looked up the exit() command but didn't really understand how to use it.

There's little not to understand about exit(). Just do:
exit(EXIT_FAILURE);
and gone's your process.
EXIT_FAILURE becomes the exit status of your program; this is the same as returning a value from main().

Since you're all in one process, though multiple threads, just hitting exit will kill the lot.

Related

Wouldn't a program with only the line of fork() break itself?

#include <unistd.h>
#include <stdio.h>
int main(){
fork();
return 0;
}
In my understanding, fork() will copy the parent's process, and run it as a child process; if that was the case, would the program above break? Because how I am understanding this program is: the program above will call fork() indefinitely, and eventually cause a Stack Overflow.
According to the POSIX specification:
Both processes shall continue to execute from the fork() function.
So, both processes will continue after the call to fork(), and both will immediately terminate.
The fork call does not make either the child or the parent process go back to the beginning of main and start over. It returns like a normal function, but it does it twice, once in the child and once in the parent, with different return values so you can tell which is which.
So, in your program, fork succeeds and then both processes go on to the return 0 and exit. Nothing bad will happen.
A variation will cause problems, though:
#include <unistd.h>
int
main(void)
{
for (;;)
fork();
/* not reached */
}
This is called a "fork bomb". Because it calls fork inside an infinite loop, never checking whether it's the parent or the child, the original process becomes two processes, and then four, and then eight, and ... until you run out of RAM, or at least process IDs. And it doesn't check for failure either, so it doesn't stop after the fork calls start failing. All of these processes will continue chewing up CPU forever, and none of the other programs running on the computer will be able to make forward progress.
Back in the days of mammoths and SunOS 4 it was even worse than that, a fork bomb would be liable to tickle a kernel bug and outright crash the minicomputer, and then the BOFH would come looking for you and he or she would not be happy. I would expect a modern kernel not to crash, and you might even be able to kill off the entire exponential process tree with control-C, but I'm not going to try it just to find out.
Incidentally, return_type whatever() is bad style in C, because for historical reasons it means whatever takes any number of arguments. Always write return_type whatever(void) instead.

How to change the meaning of SIGTERM in C program

I've recently had a problem with signals. I'd like to write a program in C which would print anything after a signal is sent to the process. For example: If I send SIGTERM to my process (which is simply running program), I want the program to print out for example, "killing the process denied" instead of killing the process. So how to do that? How to force process to catch and change the meaning of such signal. Also I have a question if there is any possibility to kill the init process (I know it's kind of a stupid question, but I was wondering how linux deals with such a signal, and how would it technically look if I type: sudo kill -9 1.
Don't use the signal handler to print. You can set a variable of type volatile sig_atomic_t instead, and have your main thread check this (see this example).
When your main thread has nothing else to do (which should be most of the time), let it block on a blocking function call (e.g. sleep()) that will wake up immediately when the signal is received (and set errno to EINTR).
C++ gotcha: Unlike the C sleep() function, std::this_thread::sleep_for() (in recent versions of glibc) does not wake up when a signal is received.
Regarding if it's possible to kill pid 1, see this question. The answer seems to be no, but I remember that Linux got very grumpy once I booted with init=/bin/bash and later exited this shell – had to hard reboot.
If you're looking for trouble, better kill pid -1.

is exit command in multithread programming exit completely?

I write a program with C. I have 3 threads which are working concurrently. (and for protecting the critical section I use semaphore). my program exit just in some situation (ending situation which provide i=by if command) which exist in thread number 2. with command: exit(-1)
When I run my program in linux, when it arrives to this condition it exit completely. But I am still not sure if all other threads exit or not? and also if they remain in memory or not? someone told me they remain as Zombie and so it could harm the system, but when I look to processes (with ps command) I saw nothing. Now I need some help about the kind of ending the all thread and also look for zombies in my system.
exit terminates the whole program, no threads are running afterwards. This might not be what you want depending on how your program is designed - no cleanup is done, threads are terminated as they are in the time of termination.

Ctrl + C: does it kill threads too along with main process?

While running a thread program and repeatedly killing the main program using Ctrl + C, i see unexpected results in the program in second run. However, if i let the program run and voluntarily exit, there are no issues.
So, my doubt is, does Ctrl + C, kill threads also along with the main process?
Thanks in advance.
In multithreaded programming, signals are delivered to a single thread (usually chosen unpredictably among the threads that don't have that particular signal blocked). However, this does not mean that a signal whose default action is to kill the process only terminates one thread. In fact, there is no way to kill a single thread without killing the whole process.
As long as you leave SIGINT with its default action of terminating the process, it will do so as long as at least one thread leaves SIGINT unblocked. It doesn't matter which thread has it unblocked as long as at least one does, so library code creating threads behind the application's back should always block all signals before calling pthread_create and restore the signal mask in the calling thread afterwards.
Well, the only thing that Ctrl + C does is sending SIGINT to one thread in the process that is not masking the signal. Signals can be handled or ignored.
If the program does handle Ctrl+C, the usual behavior is self-termination, but once again, it could be used for anything else.
In your case, SIGINT is being received by one thread, which probably does kill itself, but does not kill the others.
Under Linux 2.6 using NPTL threads: I am assuming that the process uses the default signal handler, or calls exit() in it: Yes it does. The C library exit() call maps to the exit_group system call which exits all the threads immediately; the default signal handler calls this or something similar.
Under Linux 2.4 using Linuxthreads (or using 2.6 if your app still uses Linuxthreads for some weird reason): Not necessarily.
The Linuxthreads library implements threads using clone(), creating a new process which happens to share its address-space with the parent. This does not necessarily die when the parent dies. To fix this, there is a "master thread" which pthreads creates. This master thread does various things, one of them is to try to ensure that all the threads get killed when the process exits (for whatever reason).
It does not necessarily succeed
If it does succeed, it is not necessarily immediate, particularly if there are a large number of threads.
So if you're using Linuxthreads, possibly not.
The other threads might not exit immediately, or indeed at all.
However, no matter what thread library you use, forked child processes will continue (they might receive the signal if they are still in the same process-group, but can freely ignore it)

What makes a pthread defunct?

i'm working with a multi-threaded program (using pthreads) that currently create a background thread (PTHREAD_DETACHED) and then invokes pthread_exit(0). My problem is that the process is then listed as "defunct" and curiously do not seems to "really exists" in /proc (which defeats my debugging strategies)
I would like the following requirements to be met:
the program should run function A in a loop and function B once
given the PID of the program /proc/$pid/exe, /proc/$pid/maps and /proc/$pid/fd must be accessible (when the process is defunct, they are all empty or invalid links)
it must be possible to suspend/interrupt the program with CTRL+C and CTRL+Z as usual
edit: I hesitate changing the program's interface for having A in the "main" thread and B in a spawned thread (they are currently in the other way). Would it solve the problem ?
You can either suspend the execution of the main process waiting for a signal, or don't detach the thread (using the default PHTREAD_CRATE_JOINABLE) waiting for its termination with a pthread_join().
Is there a reason you can't do things the other way round: have the main thread run the loop, and do the one-off task in the background thread?
Not the most elegant design but maybe you could block the main thread before exiting with:
while(1) {
pause();
}
Then you can install a signal handler for SIGINT and SIGTERM that breaks the loop. The easiest way for that is: exit(0) :-).

Resources