Как завершить программу переменного тока через 20 секунд - PullRequest
4 голосов
/ 19 сентября 2019

Я пытаюсь завершить свою программу c несколькими функциями через 20 секунд (уничтожить все дочерние и родительские процессы, закрыть файлы).Я пробовал будильник (), itimer (), часы ().Это работает, когда у нас есть только функция main и handler.clock () перезапускается с 0 в каждой функции, даже если я сохраняю переменные глобальными.

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <stdlib.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <getopt.h>
#include<stdbool.h>
#include <ctype.h>
#include<sys/wait.h>
#include<signal.h>
#include <sys/mman.h>
#include<sys/time.h>
#define INTERVAL 2
int t=0;
void display_message()
{
    printf("In the handler");
    //kill(0,SIGKILL);
    t=1;
}
void calling2()
{
    signal(SIGALRM, display_message);

    sleep(3);

}
void calling()
{

    signal(SIGALRM, display_message);
    alarm(2);

        int i;
        for(i=0;i<3;i++)
                {
                    //printf("\nStarting fork for loop i=%d \n",i);


                     pid_t pID = fork();

                       if (pID == 0)                // child
                       {
                           calling2();
                           if(t==1)
                           {
                               printf("we have exceeded 2 seconds killing the process");
                               kill(0,SIGKILL);
                               exit(0);
                           }
                        exit(0);
                        kill(pID,SIGKILL);
                       }
                       else if(pID>0)
                       {
                             //  printf("\nhello from the father");
                            if(t==1)
                                                       {
                                                           printf("killing the process");
                                                           kill(0,SIGKILL);
                                                           exit(0);
                                                       }
                            printf("\nhello from the father");
                       }
                }
}

Как вы можете видеть, я пытался вызывать сигнал из разных функций, чтобы он мог перехватить сигнал, и обработчик может выполнить, нообработчик никогда не выполняется.

РЕДАКТИРОВАТЬ: попробовал это снова

# include <unistd.h>
# include <sys/types.h>
# include <sys/stat.h>
# include <time.h>
# include <stdlib.h>
# include <dirent.h>
# include <stdio.h>
# include <string.h>
# include <getopt.h>
# include<stdbool.h>
# include <ctype.h>
# include<sys/wait.h>
# include<signal.h>
# include <sys/mman.h>
# include<sys/time.h>
# define INTERVAL 2
int t=0;
void display_message()
{

    kill(0,SIGKILL);
    t=1;
}
void calling2()
{

    sleep(3);

}
void calling()
{

    signal(SIGALRM, display_message);


        int i;
        for(i=0;i<3;i++)
                {

                     pid_t pID = fork();

                       if (pID == 0)                // child
                       {
                           calling2();
                           if(t==1)
                           {
                               printf("killing the process");
                               kill(0,SIGKILL);
                               exit(0);
                           }
                        exit(0);

                       }
                       else if(pID>0)
                       {
                                                        if(t==1)
                                                       {
                                                           printf("killing the process");
                                                           kill(0,SIGKILL);
                                                           exit(0);
                                                       }
                            printf("\nhello from the father");
                       }
                }
}
int main()
{
    signal(SIGALRM, display_message);
    alarm(2);
    calling();
}
O/P:
hello from the father
hello from the father
hello from the father
hello from the father
hello from the father
hello from the father
error: Failed with return code 22

1 Ответ

0 голосов
/ 19 сентября 2019

Основная проблема в том, что ваш основной поток закончен до обработки сигнала тревоги.Вы должны позволить ему жить по крайней мере, пока не будет подан сигнал тревоги.Также, как советовал Джонатан Леффлер, хороший отступ / интервал действительно полезен.

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <stdlib.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <getopt.h>
#include <stdbool.h>
#include <ctype.h>
#include <sys/wait.h>
#include <signal.h>
#include <sys/mman.h>
#include <sys/time.h>

#define INTERVAL 2
int t=0;

void display_message()
{
    kill(0,SIGKILL);
    t=1;
}

void calling2()
{

    sleep(3);
}

void calling()
{

    signal(SIGALRM, display_message);
    int i;
    for(i=0;i<3;i++)
    {
        pid_t pID = fork();
        if (pID == 0)                // child
        {
            calling2();
            if(t==1)
            {
                printf("killing the process");
                kill(0,SIGKILL);
                exit(0);
            }
            exit(0);
        }
        else if(pID>0)
        {
            if(t==1)
            {
                printf("killing the process");
                kill(0,SIGKILL);
                exit(0);
            }
            printf("\nhello from the father");
        }
    }
}

int main()
{
    signal(SIGALRM, display_message);
    alarm(2);
    calling();

    //  wait until alarm callback before terminating main thread
    sleep(100);
}
...