[linux操作系统实验]信号机制(按ctrl c给父进程发信号后,子进程没有反应?)

/ 127评论 / 1449阅读 / 1点赞

问题

按ctrl c给父进程传信号后,父进程会发送信号给子进程,为什么子进程没有反应?

而只有修改父进程给子进程发送的信号为SIGINT时才会有反应?


实验具体内容

实验内容

概念

信号的基本概念

信号的发送

对信号的处理

涉及函数

kill( )

signal( )

名  字说          明
01SIGHUP挂起(hangup)
02SIGINT中断,当用户从键盘按^c键或^break键时
03SIGQUIT退出,当用户从键盘按quit键时
04SIGILL非法指令
05SIGTRAP跟踪陷阱(trace trap),启动进程,跟踪代码的执行
06SIGIOTIOT指令
07SIGEMTEMT指令
08SIGFPE浮点运算溢出
09SIGKILL杀死、终止进程 
10SIGBUS总线错误
11SIGSEGV段违例(segmentation  violation),进程试图去访问其虚地址空间以外的位置
12SIGSYS系统调用中参数错,如系统调用号非法
13SIGPIPE向某个非读管道中写入数据
14SIGALRM闹钟。当某进程希望在某时间后接收信号时发此信号
15SIGTERM软件终止(software  termination)
16SIGUSR1用户自定义信号1
17SIGUSR2用户自定义信号2
18SIGCLD某个子进程死
19SIGPWR电源故障

源代码

#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <iostream>
#include <sys/wait.h>
#include <sys/types.h>
using namespace std;

/*记录子进程pid,
 * whois:
 *      0:父进程
 *      1:子进程1
 *      2:子进程2*/
int pid1 = 0, pid2 = 0, whois = 0;

/*信号*/
#define COOLSIG SIGINT

/*响应信号*/
void do_exit(int)
{
        switch (whois)
        {
        case 0:
        {
                kill(pid1, COOLSIG);
                kill(pid2, COOLSIG);
                cout << "<< wait1: " << wait(0) << endl;
                cout << "<< wait2: " << wait(0) << endl;
                cout << "<< 父进程退出" << endl;
        }break;
        case 1:;
        case 2:
        {
                cout << "<< 子进程" << whois << "结束!" << endl;
        }break;
        }
        exit(0);
}

int main()
{
        cout << "<< COOLSIG = " << COOLSIG << endl;
        pid1 = fork();
        if (pid1 == -1){
                cout << "<< fork error" << endl;
        }
        else if (pid1 == 0)
        {
                 whois = 1;      //子进程1
                 signal(COOLSIG, do_exit);
        }
        else
        {
                cout << "pid1 = " << pid1 << endl;
                pid2 = fork();  //父进程
             	if (pid2 == -1)
                {
                        cout << "<< fork error" << endl;
                }
                else if (pid2 == 0)
                {
                        whois = 2;      //子进程2
                        signal(COOLSIG,do_exit);
                }
                else
                {
                        cout << "pid2 = " << pid2 << endl;
                        whois = 0;      //父进程
                        signal(SIGINT, do_exit);
                        cout << "<< 父进程等待 ctrl + C ..." << endl;
                }
        }
        while (1)
                usleep(100);
        cout << "<< 退出了,whois = " << whois << endl;
        return 0;
}

运行结果截图

思考

  1. RickeyCoore说道:

    Acheter kamagra site fiable

  2. Billysow说道:

    https://esfarmacia.men/# п»їfarmacia online

  3. RickeyCoore说道:

    acheter sildenafil 100mg sans ordonnance

  4. Archiecaf说道:

    http://farmaciabarata.pro/# farmacias baratas online envГ­o gratis

  5. Archiecaf说道:

    http://pharmacieenligne.icu/# Pharmacie en ligne France

  6. ThomasLiz说道:

    п»їfarmacia online farmacias online baratas farmacias online seguras en espaГ±a

  7. Archiecaf说道:

    http://farmaciabarata.pro/# farmacia online internacional

  8. Dennislyhok说道:

    india pharmacy: canadian pharmacy india – best india pharmacy

  9. Davidjeavy说道:

    Totally! Find expos‚ portals in the UK can be crushing, but there are many resources accessible to help you think the unmatched in unison because you. As I mentioned formerly, conducting an online search representing http://www.ampheon.co.uk/perl/pags/how-old-is-will-cain-from-fox-news.html “UK scuttlebutt websites” or “British information portals” is a great starting point. Not only purposefulness this hand out you a encyclopaedic list of report websites, but it choice also provide you with a improved savvy comprehension or of the in the air hearsay prospect in the UK.
    Aeons ago you secure a liber veritatis of embryonic rumour portals, it’s critical to gauge each anyone to influence which upper-class suits your preferences. As an benchmark, BBC Intelligence is known benefit of its objective reporting of intelligence stories, while The Trustee is known for its in-depth criticism of political and popular issues. The Unconnected is known pro its investigative journalism, while The Times is known in search its vocation and investment capital coverage. During concession these differences, you can decide the information portal that caters to your interests and provides you with the newsflash you hope for to read.
    Additionally, it’s significance considering local scuttlebutt portals because proper to regions within the UK. These portals yield coverage of events and dirt stories that are applicable to the area, which can be exceptionally cooperative if you’re looking to keep up with events in your town community. For exemplar, local good copy portals in London classify the Evening Paradigm and the Londonist, while Manchester Evening News and Liverpool Repercussion are popular in the North West.
    Comprehensive, there are tons bulletin portals available in the UK, and it’s significant to do your research to see the one that suits your needs. Sooner than evaluating the unconventional news programme portals based on their coverage, dash, and article angle, you can select the individual that provides you with the most related and captivating low-down stories. Esteemed fortunes with your search, and I hope this tidings helps you discover the perfect news broadcast portal since you!

  10. FrancisFrold说道:

    cheapest online pharmacy india: cheapest online pharmacy india – india pharmacy

  11. DanielCex说道:

    Europe is a continent with a in clover representation and dissimilar culture. Lifestyle in Europe varies greatly depending on the provinces and region, but there are some commonalities that can be observed.
    United of the defining features of human being in Europe is the putrid moment on work-life balance. Diverse European countries have laws mandating a reliable amount of vacation all together seeking workers, and some experience yet experimented with shorter workweeks. This allows seeking more just the same from time to time forth with next of kin and pursuing hobbies and interests.
    https://www.machinefabriekelburg.nl/wp-content/pages/designer-anna-berezina.html
    Europe is also known in support of its wealth cultural legacy, with assorted cities boasting centuries-old architecture, aptitude, and literature. Museums, galleries, and factual sites are bountiful, and visitors can bury themselves in the record and customs of the continent.
    In addition to cultural attractions, Europe is haunt to a afield variety of natural beauty. From the dramatic fjords of Norway to the cheery beaches of the Mediterranean, there is no shortage of stunning landscapes to explore.
    Of ambit, life in Europe is not without its challenges. Varied countries are grappling with issues such as gains unevenness, immigration, and federal instability. However, the people of Europe are resilient and get a fancy history of overcoming adversity.
    Blanket, life in Europe is opulent and assorted, with something to offer for everyone. Whether you’re interested in information, refinement, nature, or unmistakably enjoying a good work-life match, Europe is a horrendous place to entitle home.

  12. AngelBop说道:

    Бурение скважин сверху воду – это процесс создания отверстий в течение поднебесной для извлечения подземных вожак, кои могут применяться чтобы разных мишеней, включая питьевую воду, увлажнение растений, промышленные необходимости а также другие: https://zenwriting.net/cracknoise1/kak-uznat-gde-burit-skvazhinu-voda. Для бурения скважин используют специальное ясс, подобное как бурильные агрегата, какие проникают в течение землю да основывают дыры глубиной через пары 10-ов ут пары сотен метров.
    После формирования скважины проводится тестирование, чтобы определить ее производительность и штрих воды. Затем щель оборудуется насосом и еще прочими системами, чтоб защитить хронический доступ к воде. Хотя бурение скважин сверху воду представляет необходимую цена на обеспечивании подхода к непорочною водопитьевой восе и утилизируется в течение разных секторах экономики промышленности, этот процесс что ль показывать негативное суггестивность сверху обступающую среду. Поэтому что поделаешь соблюдать должные правила а также регуляции.

  13. Jarvishob说道:

    Бурение скважин сверху водичку – этто эпидпроцесс организации отверстий на земле чтобы извлечения подземных вод. Эти скважины утилизируются для хозпитьевой воды, сплав растений, промышленных надобностей и остальных целей. Эпидпроцесс бурения скважин охватывает в себе эксплуатация специального оснащения, подобного яко бурильные предписания, коим проникают на грунт также создают отверстия: https://pastelink.net/b6kpq4yl. Эти скважины элементарно быть владельцем глубину от пары 10-ов до пары сотен метров.
    После создания скважины, умельцы объезжают стресс-тестирование, чтоб фиксировать ее эффективность а также штрих воды. Через некоторое время скважина снабжается насосом равным образом прочими общественный порядок, чтобы защитить постоянный доступ ко воде. Эмпайр скважин на водичку является принципиальным процессом, яже обеспечивает путь буква аккуратной хозпитьевой здесь также используется в различных секторах экономики промышленности. Однако, этот процесс что ль носить отрицательное суггестивность на брать в кольцо среду, то-то что поделаешь хранить отвечающие философия равным образом регуляции.

  14. Michaelweamp说道:

    To presume from present rumour, adhere to these tips:

    Look representing credible sources: https://lostweekendnyc.com/articles/?alarm-mode-identifying-media-coverage-that-creates.html. It’s high-ranking to guard that the expos‚ outset you are reading is reliable and unbiased. Some examples of good sources tabulate BBC, Reuters, and The Modish York Times. Interpret multiple sources to stimulate a well-rounded view of a discriminating statement event. This can support you return a more complete display and escape bias. Be in the know of the angle the article is coming from, as flush with reputable news sources can contain bias. Fact-check the information with another source if a expos‚ article seems too sensational or unbelievable. Many times fetch persuaded you are reading a current article, as news can change quickly.

    By following these tips, you can befit a more aware of rumour reader and more wisely know the beget around you.

  15. LloydKed说道:

    http://indiapharmacy.cheap/# pharmacy website india

  16. Georgespado说道:

    canadian pharmacy india: top 10 online pharmacy in india – india pharmacy

  17. ZacharyOrems说道:

    is canadian pharmacy legit pharmacies in canada that ship to the us canada drugs online reviews

  18. Georgespado说道:

    legitimate canadian pharmacy: pharmacy in canada – safe canadian pharmacy

  19. Georgeoptor说道:

    http://misoprostol.guru/# п»їcytotec pills online

  20. Michaelununk说道:

    http://lipitor.pro/# brand name lipitor

  21. Georgeoptor说道:

    http://ciprofloxacin.ink/# cipro ciprofloxacin

  22. Michaelununk说道:

    https://misoprostol.guru/# buy cytotec online

  23. Michaelununk说道:

    http://lipitor.pro/# lipitor 10mg price comparison

  24. Georgeoptor说道:

    https://avodart.pro/# can i buy cheap avodart pill

  25. Michaelununk说道:

    http://lisinopril.pro/# zestril 5 mg

  26. RobertBog说道:

    Paxlovid buy online: paxlovid pharmacy – paxlovid pill

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注