Reputation: 3
How do I kill old parent processes within a for loop? I have the following that forks a parent process
if (pid > 0){
pid_t ppid = getppid();
for (int parentid = ppid; parentid > 1; parentid++) {
parentid = ppid;
pid_t ppid = fork();
if(ppid > 1) {
execl("/usr/bin/elinks","elinks","google.com",(char *) NULL);
}
sleep(5);
}
exit(EXIT_SUCCESS);
}
I have a child process continously running throughout
system("xdotool......")
I tried putting kill(ppid,SIGTERM) within the for loop but it was ignored. Only placing it after the loop does the kill signal but then the entire program quits. The parent forks keep stacking up and consuming ram so its necessary for me to kill the old parent when a new parent is created.
Upvotes: 0
Views: 223
Reputation: 4148
You also need to make sure there is a proper termination condition for your for loop:
pid_t ppid = getppid();
for (int parentid = ppid; parentid > 1; parentid++) {
parentid = ppid;
pid_t ppid = fork();
Are you sure your for loop ends as you expect?
If parentid is always greater than 1 because fork() succeeded, how
does the loop terminate?
The fork function returns 0 to the child process, and the PID of the child to the parent process.
Therefore, you can use this code to determine whether the code that is executing is the child or parent:
pid_t pid = fork();
if (pid == 0)
{
/* At this point, the code that is executing is the child */
}
else if (pid > 0)
{
/* At this point, the code that is executing is the parent */
}
else
{
/* The fork function call failed */
}
Your code needs to differentiate between the child and the parent; you can use the exit system call in the block of code above for the parent.
Upvotes: 1