Sie sind auf Seite 1von 7

4/24/12

C/C++ signal handling

C/C++signalhandling
CandC++signalhandlingandC++signalclassesandexamples.

TutorialTableofContents: #SignalDescription,Types #Csignalhandling #C++SignalClass #CManPages search


RelatedYoLinux Tutorials:

Search

|HomePage|LinuxTutorials|Terms|PrivacyPolicy|Advertising|Contact|

Signals:
Description:Signalsaresoftwareinterruptsdeliveredtoaprocessbythe operatingsystem.Signalscanalsobeissuedbytheoperatingsystembasedon systemorerrorconditions.Thereisadefaultbehaviorforsome(i.e.aprocess isterminatedwhenitreceivesaninturruptSIGINTsignalbypressingkeystrokes ctrlC)butthistutorialshowshowtohandlethesignalbydefiningcallback functionstomanagethesignal.Wherepossible,thisallowsonetoclosefiles andperformoperationsandreactinamannerdefinedbytheprogrammer. Notethatnotallsignalscanbehandled. Typesofsignals: Signal SIGHUP Value 1 Description Hangup(POSIX) Reportthatuser'sterminalisdisconnected.Signal usedtoreporttheterminationofthecontrolling process. Interrupt(ANSI) Programinterrupt.(ctrlc) Quit(POSIX) Terminateprocessandgeneratecoredump. IllegalInstruction(ANSI) Generallyindicatesthattheexecutablefileis corruptedoruseofdatawhereapointertoa functionwasexpected. Tracetrap(POSIX) Abort(ANSI) IOTtrap(4.2BSD) Processdetectserrorandreportsbycallingabort BUSerror(4.2BSD) Indicatesanaccesstoaninvalidaddress. FloatingPointarithmeticException(ANSI). Thisincludesdivisionbyzeroandoverflow.The IEEEStandardforBinaryFloatingPointArithmetic (ANSI/IEEEStd7541985)definesvariousfloating pointexceptions.

LinuxandC++ C++Unions&Structures C++STL C++STLMap C++StringClass C++Singleton C++CodingStyle C++XMLBeans C/C++DynamicMemory C++MemoryCorruption C++CGI YoLinuxTutorialsIndex

SIGINT SIGQUIT SIGILL

2 3 4

SIGTRAP SIGABRT SIGIOT SIGBUS SIGFPE

5 6

7 8

www.yolinux.com/TUTORIALS/C++Signals.html

1/7

4/24/12

C/C++ signal handling

SIGKILL SIGUSR1 SIGSEGV

9 10 11

Kill,unblockable(POSIX) Causeimmediateprogramtermination. Cannotbehandled,blockedorignored. Userdefinedsignal1 SegmentationViolation(ANSI) Occurswhenaprogramtriestoreadorwrite outsidethememorythatisallocatedforitbythe operatingsystem,dereferencingabadorNULL pointer.Indicatesaninvalidaccesstovalid memory. Userdefinedsignal2 Brokenpipe(POSIX) Errorconditionliketryingtowritetoasocketwhich isnotconnected. Alarmclock(POSIX) Indicatesexpirationofatimer.Usedbythealarm() function. Termination(ANSI) Thissignalcanbeblocked,handled,andignored. Generatedby"kill"command. Stackfault Childstatushaschanged(POSIX) Signalsenttoparentprocesswheneveroneofits childprocessesterminatesorstops. SeetheYoLinux.comFork,exec,wait,waitpid tutorial Continue(POSIX) Signalsenttoprocesstomakeitcontinue. Stop,unblockable(POSIX) Stopaprocess.Thissignalcannotbehandled, ignored,orblocked. Keyboardstop(POSIX) Interactivestopsignal.Thissignalcanbehandled andignored.(ctrlz) Backgroundreadfromtty(POSIX) Backgroundwritetotty(POSIX) Urgentconditiononsocket(4.2BSD) Signalsentwhen"urgent"oroutofbanddata arrivesonasocket. CPUlimitexceeded(4.2BSD) Filesizelimitexceeded(4.2BSD) VirtualTimeAlarm(4.2BSD) Indicatesexpirationofatimer. Profilingalarmclock(4.2BSD) Indicatesexpirationofatimer.Useforcode profilingfacilities. Windowsizechange(4.3BSD,Sun) I/Onowpossible(4.2BSD) Pollableeventoccurred(SystemV) Signalsentwhenfiledescriptorisreadytoperform I/O(generatedbysockets) Powerfailurerestart(SystemV)

SIGUSR2 SIGPIPE

12 13

SIGALRM

14

SIGTERM

15

SIGSTKFLT 16 SIGCHLD SIGCLD 17

SIGCONT SIGSTOP
AdsbyGoogle

18 19

Signal C++Programming C++Tutorial FreeInformation Technology Magazinesand DocumentDownloads

SIGTSTP

20

Advertisement LevonoUK:

SIGTTIN SIGTTOU SIGURG

21 22 23

SIGXCPU SIGXFSZ

24 25

SIGVTALRM 26 SIGPROF 27

SIGWINCH SIGIO SIGPOLL

28 29

SIGPWR

30

SIGSYS 31 Badsystemcall See:/usr/include/bits/signum.h Signalswhichcanbeprocessedinclude:SIGINT,SIGABRT,SIGFPE,SIGILL,

www.yolinux.com/TUTORIALS/C++Signals.html

2/7

4/24/12

C/C++ signal handling


SIGSEGV,SIGTERM,SIGHUP

Listallsignalsavailabletothesystem: Usethecommand:killl
$killl 1)SIGHUP2)SIGINT3)SIGQUIT4)SIGILL 5)SIGTRAP6)SIGABRT7)SIGBUS8)SIGFPE 9)SIGKILL10)SIGUSR111)SIGSEGV12)SIGUSR2 13)SIGPIPE14)SIGALRM15)SIGTERM17)SIGCHLD 18)SIGCONT19)SIGSTOP20)SIGTSTP21)SIGTTIN 22)SIGTTOU23)SIGURG24)SIGXCPU25)SIGXFSZ 26)SIGVTALRM27)SIGPROF28)SIGWINCH29)SIGIO 30)SIGPWR31)SIGSYS34)SIGRTMIN35)SIGRTMIN+1 36)SIGRTMIN+237)SIGRTMIN+338)SIGRTMIN+439)SIGRTMIN+5 40)SIGRTMIN+641)SIGRTMIN+742)SIGRTMIN+843)SIGRTMIN+9 44)SIGRTMIN+1045)SIGRTMIN+1146)SIGRTMIN+1247)SIGRTMIN+13 48)SIGRTMIN+1449)SIGRTMIN+1550)SIGRTMAX1451)SIGRTMAX13 52)SIGRTMAX1253)SIGRTMAX1154)SIGRTMAX1055)SIGRTMAX9 56)SIGRTMAX857)SIGRTMAX758)SIGRTMAX659)SIGRTMAX5 60)SIGRTMAX461)SIGRTMAX362)SIGRTMAX263)SIGRTMAX1 64)SIGRTMAX

Sendingaprocessasignal: Aprocesscanbesentasignalusingthe"kill"command:killssignal
numberpid

Wherethepid(processid)canbeobtainedusingthe"ps"command.

CSignalhandlerandExample:
BasicCsignalcallbackfunctionexample: File:signalExample.cpp

01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

#include<stdio.h> #include<stdlib.h> #include<signal.h>

//Definethefunctiontobecalledwhenctrlc (SIGINT)signalissenttoprocess void signal_callback_handler(intsignum) { printf("Caughtsignal%d\n",signum) //Cleanupandcloseupstuffhere

//Terminateprogram exit(signum) }

intmain() { //Registersignalandsignalhandler signal(SIGINT,signal_callback_handler)

while(1) { printf("Programprocessingstuffhere.\n") sleep(1) } returnEXIT_SUCCESS }

Exampletohandlectrlc Compile:gccsignalExample.cpp

www.yolinux.com/TUTORIALS/C++Signals.html

3/7

4/24/12

C/C++ signal handling

Run:a.out Results:
Programprocessingstuffhere. Programprocessingstuffhere. Caughtsignal2

Thefunctionprototype:void(*signal(intsig,void(*func)(int)))(int)

C++SignalRegistrationandHandlingClass:
File:signalHandler.hpp

01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

#ifndef__SIGNALHANDLER_H__ #define__SIGNALHANDLER_H_ #include<stdexcept> usingstd::runtime_error

classSignalException:publicruntime_error { public: SignalException(conststd::string&_message) :std::runtime_error(_message) {} }

classSignalHandler { protected: staticboolmbGotExitSignal

public: SignalHandler() ~SignalHandler()

staticboolgotExitSignal() staticvoidsetExitSignal(bool_bExitSignal) voidsetupSignalHandlers() staticvoidexitSignalHandler(int_ignored) } #endif

File:signalHandler.cpp

01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23

#include<signal.h> #include<errno.h>

#include"signalHandler.hpp boolSignalHandler::mbGotExitSignal=false /** *DefaultContructor. */ SignalHandler::SignalHandler() { }

/** *Destructor. */ SignalHandler::~SignalHandler() { }

/** *Returnstheboolflagindicatingwhetherwereceived anexitsignal

www.yolinux.com/TUTORIALS/C++Signals.html

4/7

4/24/12
25 24 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58

C/C++ signal handling


*/ *@returnFlagindicatingshutdownofprogram boolSignalHandler::gotExitSignal() { returnmbGotExitSignal }

/** *Setstheboolflagindicatingwhetherwereceivedan exitsignal */ voidSignalHandler::setExitSignal(bool_bExitSignal) { mbGotExitSignal=_bExitSignal }

/** *Setsexitsignaltotrue. *@param[in]_ignoredNotusedbutrequiredbyfunction prototype *tomatchrequiredhandler. */ voidSignalHandler::exitSignalHandler(int_ignored) { mbGotExitSignal=true }

/** *SetupthesignalhandlersforCTRLC. */ voidSignalHandler::setupSignalHandlers() { if(signal((int)SIGINT, SignalHandler::exitSignalHandler)==SIG_ERR) { throwSignalException("!!!!!Errorsettingup signalhandlers!!!!!") } }

File:test.cpp

01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

#include<iostream> #include"signalHandle.hpp" usingnamespacestd

main() { intiret

try { SignalHandlersignalHandler

//Registersignalhandlertohandlekillsignal signalHandler.setupSignalHandlers() //Infiniteloopuntilsignalctrlc(KILL) received while(!signalHandler.gotExitSignal()) { sleep(1) }

iret=EXIT_SUCCESS } catch(SignalException&e) { std::cerr<<"SignalException:"<<e.what()<< std::endl iret=EXIT_FAILURE } return(iret) }

www.yolinux.com/TUTORIALS/C++Signals.html

5/7

4/24/12

C/C++ signal handling

Compile:g++signalHandle.cpptest.cpp

CSignalManPages:
Cfunctions: signalANSICsignalhandling raisesendasignaltothecurrentprocess strsignalreturnstringdescribingsignal(GNUextension) psignalprintsignalmessage sigactionPOSIXsignalhandlingfunctions sigsetopsPOSIXsignalsetoperations sigvecBSDsoftwaresignalfacilities alarmsetanalarmclockfordeliveryofasignal Commands: killterminateaprocess psreportasnapshotofthecurrentprocesses.

Books:
C++HowtoProgram byHarveyM.Deitel,PaulJ.Deitel ISBN#0131857576,PrenticeHall Fifthedition.Thefirsteditionofthis book(andProfessorSheelyatUTA) taughtmetoprogramC++.Itis completeandcoversallthenuances oftheC++language.Italsohas goodcodeexamples.Goodforboth learningandreference. "AdvancedUNIXProgramming" SecondEdition byMarcJ.Rochkind ISBN#0131411543,Addison WesleyProfessionalComputing Series

"AdvancedProgramminginthe UNIXEnvironment"FirstEdition byW.RichardStevens ISBN#0201563177,Addison WesleyProfessionalComputing Series ItistheCprogrammersguideto programmingontheUNIXplatform. Thisbookisamustforanyserious UNIX/Linuxprogrammer.Itcoversall oftheessentialUNIX/LinuxAPI's andtechniques.Thisbookstarts wherethebasicCprogramming bookleavesoff.Greatexamplecode. Thisbooktravelswithmetoevery jobIgoto.

www.yolinux.com/TUTORIALS/C++Signals.html

6/7

4/24/12

C/C++ signal handling

"UNIXNetworkProgramming, Volume1:NetworkingAPIs SocketsandXTI"SecondEdition byW.RichardStevens ISBN#013490012X,PrenticeHall PTR ThisbookcoversnetworkAPIs, sockets+XTI,multicast,UDP,TCP, ICMP,rawsockets,SNMP,MBONE. Indepthcoverageoftopics. "UNIXNetworkProgramming Volume2:Interprocess Communications" byW.RichardStevens ISBN#0130810819,PrenticeHall PTR Thisbookcoverssemaphores, threads,recordlocking,memory mappedI/O,messagequeues, RPC's,etc. "AdvancedUnixProgramming" byWarrenW.Gay ISBN#067231990X,SamsWhite BookSeries Thisbookcoversalltopicsin general:files,directories,date/time, libraries,pipes,IPC,semaphores, sharedmemory,forkedprocesses andI/Oscheduling.Thecoverageis notasindepthastheprevioustwo books(StevensVol1and2)

YoLinux.comHomePage YoLinuxTutorialIndex|Terms PrivacyPolicy|Advertisewithus|FeedbackForm| Unauthorizedcopyingorredistributionprohibited.

UnixToLinuxMigration
ProvidedByDellIndiaToIncreaseefficiency
www.Dell.com/unixtolinux

Copyright2010byGregIppolito

www.yolinux.com/TUTORIALS/C++Signals.html

7/7

Das könnte Ihnen auch gefallen