I 'm trying to do a socket programming example with using fork() call, my problem is: When a child process finished a job, i want to kill all other process. I think if i send a singal to others ... Is this possible or is any one tell me a way ?
At the start of the partent (before it forks its children), call setpgid(0,0). This will get the Process Group ID to the the same as the parent's PID. This PGID will be inherited by each child and any of the processes can send a signal to all processes in the group by calling kill(signal, -getpgid(0)).
An usual way of kill a process group is with killpg() system call. From man pages:
"killpg() sends the signal sig to the process group pgrp."
Along with killpg(), get/setpgid might be needed also to setup a group properly.
You can use this:
killpg( 0, SIGNALTYPE);
You can send signal to all childs.
Related
I am developing a server program that serves multiple clients by multiple child processes. I use only one System V message queue to communicate between parent process and child processes. Each process will wait for message with mtype equals to process ID. Each child process only communicate to parent process. In parent process, I call msgrcv with flag IPC_NOWAIT to prevent being blocked to process other stuffs. With 2 child processes, it works as expect, but when number of child processes increases, the issue will happen as follow:
If I set flag on msgsnd to IPC_NOWAIT, some child processes cannot send message to parent process with error EAGAIN. If I add mechanism to re-send message with this kind of error, it still fails and parent process doesn't receive an message.
If I unset flag on msgsnd from IPC_NOWAIT, some child processes will be blocked in this call to msgsnd function. The parent process doesn't receive any message.
So:
How can I fix this issue?
If not, can you recommend me an architect to solve my problem?
My system is Centos 7. The message has size of 300 bytes.
Code is not given. Best is to check return values of failure and refer manpage . On gdb you can single step through to get to point where child process fails to send message
In my process I need to start/restart another process.
Currently I use a thread with a tiny stack size and the following code:
void startAndMonitorA()
{
while(true)
{
system("myProcess");
LOG("myProcess crashed");
usleep(1000 * 1000);
}
}
I feel like that's not best practice. I have no idea about the resources the std::system() call is blocking or wasting. I'm on an embedded Linux - so in general I try to care about resources.
One problematic piece is restarting immediately: if the child process fails to start that is going to cause 100% CPU usage. It may be a transient error in the child process (e.g. cannot connect to a server). It may be a good idea to add a least one second pause before trying to restart.
What system call does on Linux is:
Sets up signals SIGINT and SIGQUIT to be ignored.
Blocks signal SIGCHLD.
fork()
Child process calls exec() shell, passing the command line to the shell.
Parent process calls waitpid() that blocks the thread till the child process terminates.
Parent process restores its signal dispositions.
If you were to re-implement the functionality of system you would probably omit step 5 (along with steps 1, 2 and 6) to avoid blocking the thread and rely on SIGCHLD to get notified when the child process has terminated and needs to be restarted.
In other words, the bare minimum would be to set up a signal handler for SIGCHLD and call fork and exec.
The code as shown would be adequate for most circumstances. If you really care about resource usage, you should be aware that you are starting (and keeping around) a thread for each process you are monitoring. If your program has an event loop anyway, that kind of thing can be avoided at the cost of some additional effort (and an increase in complexity).
Implementing this would entail the following:
Instead of calling system(), use fork() and exec() to start the external program. Store its PID in a global table.
Set a SIGCHLD handler that notifies the event loop of the exit of a child, e.g. by writing a byte to a pipe monitored by the event loop.
When a child exits, run waitpid with the WNOHANG flag in a loop that runs for as long as there are children to reap. waitpid() will return the PID of the child that exited, so that you know to remove its PID from the table, and to schedule a timeout that restarts it.
How can I measure the memory used by a child process after I call fork and exec? Basically I want to be able to write code that corresponds to the following
if (!fork()) {
// run child process
exec();
} else {
while (child active) {
print memory used by child
}
}
There are two things that I do not know here, how can I see if the child process has finished running? Will I have to use some sort of process level mutual exclusion here? If yes then what is a structure I can use? Can I just use the OS filesystem for this purpose?
Also I was looking at the answer at this link Differences between fork and exec, in paragraph 8 the author says copy on write is useful when process calls fork without calling exec. But isn't this true more in the case when the parent calls fork and does not call exec? When the parent calls exec the virtual address space of the child is wiped out and replaced with the one resulting from the new program loaded into memory correct?
Thank you!
Regarding the above comment chain which I evidently can't reply to because I don't have 50 rep:
The return value of fork in the parent if successful is the PID of the child. You should probably save the return value so you can 1. wait on the correct child (if you have more than one), and 2. see if fork fails (in which case you probably don't want to loop until the child exits ).
You could also use signals to figure out when the child dies instead of continuously trying to wait with the WNOHANG option. The process will send SIGCHLD to the parent when it terminates (or stops) and if it died then you can wait on it with waitpid and stop your loop. see:
man 7 signal
man 2 sigaction
for more information on this.
regarding memory usage, it seems you either want /proc/[pid]/statm or /proc/[pid]/stat.
man 5 proc will give you all the information about what is in those files.
I have a long-running console-based application Sender that sends simple text to STDOUT using non-buffered output such as cout << "Message" << flush(). I want to create an MFC dialog-based application (named Receiver) that starts Sender and can read it's output. Receiver should also be able to detect when Sender has died, or be able to kill Sender if it wants to. Sender knows nothing of Reciever, and I can't change Sender's code.
My first attempt was to create pipes with redirected STDIN and STDOUT for the child process and use asynchronous ReadFileEx calls to read in Sender's data. This isn't working correctly, and I've posted a separate thread about those specific problems.
My question is, how should I be doing this, in general architectural terms? I don't want Receiver's main loop to block or poll, but should use some flavor of Wait function.
You have 2 basic options. Option 1 you've already tried, doing asynchronous (aka nonblocking) IO to read/write from the child process. Option 2 is to create a separate thread in the Receiver process that does blocking reads/writes from/to the child process.
I'd recommend option 2, I find it much easier. You then, of course, have the problem of how to get the data from the helper thread to the main thread. You'll need to use locks and maybe semaphores for that. It should be less of a hassle than nonblocking IO, however.
I wrote a program that forks some processes with fork(). I want to kill all child- and the mother process if there is an error. If I use exit(EXIT_FAILURE) only the child process is killed.
I am thinking about a system("killall [program_name]") but there must be a better way...
Thank you all!
Lennart
Under UNIX, send SIGTERM, or SIGABRT, or SIGPIPE or sth. alike to the mother process. This signal will then be propagated to all clients automatically, if they do not explicitely block or ignore it.
Use getppid() to get the PID to send the signal to, and kill() to send the signal.
getppid() returns the process ID of
the parent of the calling process.
The kill() system call can be used to send any signal to any process group or process.
Remarks:
1. Using system is evil. Use internal functions to send signals.
2. killall would be even more evil. Consider several instances of your program running at once.
See How to make child process die after parent exits?
On Linux there's a prctl() call which is explicitly designed to send a signal to all of a process's children when the parent dies for whatever reason.
I need to check and can't do it where I am at the second, but I'm really not sure that ypnos' assertion about SIGPIPE, SIGTERM and SIGABRT being propagated to all children is correct.
However if you use kill(-ppid) (note the minus sign) then so long as the children are still in the parent process's process group then the kernel will deliver any signal to all of the children.
If your mother process is not started by the command line, it may not be the
process group leader, like as a deamon.
To ensure that your mother process is the process group leader, call setsid() during
your process initialization.
Then in your child process, if you want to cause all the processes to exit:
pgid = getpgid();
kill(pgid, 15);
You can also do tricks, like telling all your siblings to suspend:
kill(pgid, 20);
And resume:
kill(pgid, 18);
Consider suicidal approach - setting up an alarm() at the beginning of the process (both parent and child) with some positive number of seconds. If computation completes within that time and "there is no error", call alarm(0) to cancel the timer; otherwise the SIGALRM will kill the process (assuming you're not explicitly catching or ignoring it.)
Well, make a case against this instead of just down-voting :)