Top Banner
55

Beginning Linux Programming by Knowledge Flow

Nov 08, 2015

Download

Documents

damirprc

linux programming
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • LEARNINGSTARTSWITHVIEWINGTHEWORLDDIFFERENTLY.

    Knowledgeflow-Amobilelearningplatformprovidesapps,eBooksandvideotutorials.

    KnowledgeflowbringsyoualearningeBookofBeginningLinuxProgramming.ThiseBookisforallinformationtechnologyandcomputersciencestudentsandprofessionalsacrosstheworld.

    Followuson

    Facebook

    Googleplus

    Twitter

    Formoreinformationvisitusat

    Knowledgeflow.in

    knowledgeflowapps.blogspot.inThankyouforusingKnowledgefloweBooks

  • BEGINNINGLINUXPROGRAMMING1.Introduction

    2.ArchitectureofLinux

    3.DevelopmentandHardwaresupport

    4.UsesofLinux

    5.Linuxfiletree

    6.Commandlinearguments

    7.Controloperators

    8.Filesub-system

    9.Bash,Commandshell,PipingandRe-direction

    10.WorkingwithLinuxfilesanddirectories

    11.ShellscriptinginLinux

    12.ListofOS

    13.MoreeBooksandApps

    14.OureBooksonITandComputerScience

  • DisclaimerThiseBookcontentsisforinformationalandstudypurposesonly.TheKnowledgeflowmakesnoclaims,promises,orguaranteesabouttheaccuracy,completeness,oradequacyofthecontentsofthiseBookandnolegalliabilityorotherresponsibilityisacceptedbyKnowledgeflowforanyerrors,omissions,orstatementsonthiseBook.

  • IntroductionLinuxisaUnix-likecomputeroperatingsystemassembledinsupervisionforbeingthemodeloffreeandopen-sourcesoftwaredevelopmentaswellasdistribution.ThereforethemostdefiningcomponentistheLinuxkernelthatisanoperatingsystemkernelthatwasfirstreleasedbyLinusTorvaldsonthedate5Octoberofyear1991.TheOpensourceaswellasfreeSoftwareFoundationusesthenameLinuxtodescribetheoperatingsystemthatwasabigcontroversy.LinuxwasdevelopedtobeafreeoperatingsystemforIntelx86whichwasbasedonpersonalcomputerbutithasalsobeenportedtomostofthecomputerhardwareplatformsthananyotheroperatingsystem.Atpresentithasbeentheleadingoperatingsystemonserversaswellasonotherbigironsystemssuchasmainframecomputersandalsointhesupercomputers,stillitisusedonlyaround1.5%ofdesktopcomputersatpresentcomputingscenario.Linuxcanrunonembeddedsystemswhodevicesareoperatingsystemwhichistypicallymadeintothefirmwareandisalsohighlytailoredtotheparticularsystemthisparticularsystemalsoincludesmobilephones,computers,tablets,networkrouters,televisionsandevenvariousvideogameconsoles.AndroidOSisalsobasedontheLinuxkernel.

    Tuxthepenguin,MascotofLinux

    CreationofLinux

  • TorvaldsstarteddevelopmentoftheLinuxkernelandalsomadetheapplicationswrittenforMINIXtobeusedonLinux.AftersometimelatertheLinuxmaturedandalsotheLinuxkerneldevelopmentalongwiththereplacementofGNUwiththeMINIXcomponentsalsotookplacesinceitwasanadvantagetousefreeofcostavailablecodefromtheparticularGNUProjectwiththefledglingOS.TorvaldsalsoswitchedfromtheoriginallicenseofhisownwhichprohibitedcommercialredistributionoftheGNUGPL.AlsothevariousdevelopersworkedtointegrateGNUcomponentsalongwiththeLinuxkerneltomakeitafreeoperatingsystem.

    Recentdevelopment

    Torvaldscontinuesthefurtherdevelopmentofthekernel.Finallywiththehelpofindividualsandcorporationsdevelopthirdpartyfornon-GNUcomponents.Thethirdpartycomponentscompriseofavastbodyoftheworkandmayalsoincludeboththekernelmodulesalongwiththeusersapplications.

    ReasonforusingLinux

    Givesfreedomtoruntheprogramirrespectiveofthepurpose.Givesfreedomtostudyhowtheprogramworksandalsoallowstomakechangesyouwishtomake.Toredistributethecopiessothatyoucanhelpyourneighbortoo.Alsoallowsdistributioncopiesfreelyofyourmodifiedversions.

  • DesignofLinuxLinux-basedsystemisamoduleoftheUnix-likeoperatingsystem.MuchofthebasicdesignsarederivedfromprinciplesestablishedinUNIXintheperiodofyear1970sand1980s.ThiskindofsystemusesamonolithickernelandtheLinuxkernelalongwithfilesystemaccess.Inthisthedevicedriversareeitherintegrateddirectlywiththekernelorareaddedasamoduleloadedwhilethesystemisinarunningstate.Separateprojectsthatareinterfacedwiththekernelprovidethesystemsmostofthehigher-levelfunctionality.GNUisanimportantpartofmostLinux-basedsystemssinceitisresponsibleforprovidingthemostcommonimplementationoftheClibraryandmanycommonUNIXtoolswhichcarriesoutbasicoperatingsystemtasks.ThisgraphicaluserinterfaceisusedbymostoftheLinuxsystemsbuiltonthetopofanimplementationoftheWindowSystem.

    ArchitectureofLINUXkernel

    ComponentsofLinux

    VariouscomponentsinstalledofaLinuxsystemareasfollows-

    Bootloader.ExampleGNUGRUB,SYSLINUX,Gummibootetc.LoadsLinuxkerneltocomputersmainmemorywhichisbeingexecutedby

  • computerwhenturnedonandafterinitializationofframeworkisperformed.ProgramslikethetraditionalsysvinitandUpstart.FirstprocesslaunchedbytheLinuxkernelwhichisalsoattherootoftheprocesstreesthatmeansallprocessesareusuallylaunchedbyinit.Itstartsprocessessuchasasystemservicesandloginprompts.Softwarelibrariescontaincodethatcanbeeasilyusedbyrunningprocesses.InLinuxsystemsusingELF-formatexecutablefileisadynamiclinkerthatcanmanagesuserofdynamiclibrariesthatiscalledld-linux.so.Theheaderfilesarealsoincludedfordescribingtheinterfaceofaninstalledlibrary.WidgettoolkitsareusedtobuildvariouscharacterizedGUIforthesoftwareapplications.LibrariesareprimarilydevelopedbytheEnlightenmentteam.Userinterfaceprogramsusedaresuchasthecommandshellsorthewindowingenvironments.

    Theuserinterfaceknownastheshellwhichisacommand-lineinterface(CLI),agraphicaluserinterfaces(GUI)whichiscommonforanyembeddedsystems.

    UserInterface

    CLIshellsarethetext-baseduserinterfacesthatusetextforbothinputandoutput.ThesearedominantshellwhichisusedinLinuxwhichistheGNUBourne-AgainShellalsoknownasBASHthatisoriginallydevelopedfortheGNUproject.Mostlow-levelLinuxcomponents.TheCLIissuitedforautomationofrepetitiveaswellasdelayedtasks.AwindowmanagerprovidesamethodortoolbywhichtocontroltheplacementandtheappearanceoftheindividualapplicationwindowsanditcaninteractswiththeXWindowSystemalso.Thedesktopenvironmentsjustincludewindowmanagersaspartoftheirstandardinstallationsalthoughtheusermightprefertouseadifferentwindowmanageralsoifneeded.Waylandcompositorhasaroleofthedisplayserver,windowmanageraswellascompositingmanager.

  • DevelopmentinLinuxThemostimportantdifferencebetweenLinuxandmostoftheotherpopularcontemporaryoperatingsystemsarethatthekernelusedinLinuxthatistheLinuxkernelaswellasvariousothercomponentsarefreeofcostandalsoopensourcesoftware.Thereexistsomefreeaswellasopensourcesoftwarewhoselicensesarebasedonthevariousprinciplesofcopyleftandakindofreciprocity.Anyworkthatisderivedfromacopyleftpieceofthesoftwaremustalsobeacopyleftit.ThemostcommonfreelicensingistheGNUGeneralPublicLicense(GPL)thatisalsoaformofcopyleftandisusedfortheLinuxkernel.WhereasmanyofthecomponentsareusedfromtheGNUProject.Freesoftwareprojectsthataredevelopedthroughcollaborationareoftenproducedindependentlyforeachother.

    SimplifiedUNIXlikearchitecture

  • HardwaresupportinLinuxLinuxkernelisanoperatingsystemkernelcanrunonaveryhighanddiverserangeofcomputerarchitecturesthatalsoincludethehandheldandARMbasediPAQeitherwiththeIBMmainframessystemz9orwithSystemz10thatwouldhelpincoveringthedevicesthatwouldrangefrommobilephonestothesupercomputers.Specializeddistributionsofkernelforksexistforlessmainstreamarchitectures.SuchastheELKSkernelforkcanrunonIntel8086aswellasIntel8028616-bitmicroprocessorswhereastheClinuxkernelforkmayrunonsystemswithoutamemorymanagementunit.Thekernelrunsonarchitecturesthatwereintendedtouseamanufacturer-createdoperatingsystemliketheMacintoshcomputers,variousvideogameconsolesanddifferenttypesofmobilephones.

    Linuxinvarioustypesofhardware

    Itisalsousedinvariousportablemusicplayers.Variousindustryassociationsaswellashardwareconferencesaredevoted

  • tomaintainandalsoimprovesupportforvariousdiversehardwareunderLinux,forane.g.FreedomHEC.WithtimethesupportsystemfordifferenthardwarehasimprovedinLinux.Asaresultinmanyofftheshelfpurchasesarehavingabetterofbeingcompatible.Itprovidesapoolofopenandprioritysoftwarewhichhelpstheusertocustomizeanduseinaccordancetohisneedsandpriority.ShellnamedbashwaswidelyusedbyLinux.BashwasaproductwhichwasdevelopedbyGNU.

    BashdevelopedbyGNU

  • UsesofLinuxTheLinuxdistributionsbesidewasdesignedmostlyforthegeneralpurposesthatarebeperformedonthedesktopsaswellasservers.Thereforefurtherthedistributionshavetobespecializedforvariousotherpurposesthatincluded-computerarchitecturesupport,security,embeddedsystems,andlocalizationtoaspecificregion,stabilityandsupportforreal-timeapplications.Therearesomemoredistributionswhichdeliberatelyincludeonlyaccountingthefreesoftware.

    Desktop

    ThepopularityofLinuxnowadayonthestandarddesktopcomputersaswellasthelaptopshasbeenincreased.CurrentlymostdistributionsthataredoneincludeagraphicaluserenvironmentwiththetwoofthemostpopularenvironmentsthatareGNOMEandKDEPlasmaDesktop.TherenoexistenceofasingleLinuxdesktop-RatherdesktopenvironmentsaswellasLinuxdistributionsselectcomponentsfromthepooloffreeopen-sourcesoftwarewhichtheyusetoconstructaGUIimplementingsomemoreorlessstrictdesigningguidance.GNOMEcanbestatedasoneoftheexamplesforthehumaninterfaceguidelineswhichgivesthehumanmachineinterfacenotjustaplatformtoperformthegraphicaldesignbutalsoconsiderspeoplewithdisabilitiesandstillevenwhenfocusingonsecurity.NatureofcollaborationoffreesoftwaredevelopmentallowsperforminglanguagelocalizationforsomeoftheLinuxdistributionsfortheuseinlocaleswherethelocalizingproprietarysystemswouldnotbeeffectiveincostwise.

  • SoftwarecomponentsofLinuxkernel

    Servers,mainframesandsupercomputersIthavelongbeenusedasserveroperatingsystemsthathaverisentoprominenceinthatareaofNetcraftreportedthateightofthetenarethemostreliableinternethostingcompaniesrunningLinuxdistributionsonvariouswebservers.Ithavebeenthecornerstoneandstillcontinuestobe,fortheLAMPserverandsoftwarecombinationwhichachievedfameamongvariousdevelopersandalsoisoneofthemostcommonplatformsusedforhostingwebsite.Itdistributionshavebecomeincreasinglypopularonmainframesinthelastdecadepartlyduetopricingandtheopen-sourcemodel.Linuxdistributionsarealsocommonlyusedasoperatingsystemsforsupercomputers.AndinthedecadetilltheEarthSimulatorsupercomputerallthefastestsupercomputershaveworkedwithLinux.

  • Lampsoftware

    Embeddeddevices

    Sinceitslowcostandeasytocustomizeitiswidelyusedasthefavoriteinembeddedsystems.Non-mobiletelecommunicationsequipmentmajorityofcustomerpremisesequipmenthardwarearerunningonvariousLinux-basedOS.OpenWrtiscommunitydrivenelementonwhichmanyOEMfirmwaresaredependent.

    Specializeduses

    Duetotheflexibility,freeandalsobeingaopensourcebynatureithasbecomepossibletohighlytunedLinuxforaspecifiedpurposes.

    TherearetwomainmethodsforcreatingaspecializedLinux-

    fromscratchfromageneralpurposedistribution

    Avoidingresourceoverheadhascausedbythecomponentsareconsideredtoberedundantinthedistribution.

  • LinuxfiletreeContentsoftheLinuxfiletreesareasfollows.

    /bin-Commonprograms,itissharedbythesystem,thesystemadministratoraswellaswiththeusers./boot-Inrecentdistributionshadalsogrubdatas.ThereforeGrubstandsfortheGrandUnifiedBootloaderthatisanattempttogetridofthemanyotheravailableboot-loaders./dev-ItconsistsaelementthatreferencestoalltheCPUperipheralhardwarethatarerepresentedasfileswithspecialproperties./etc-Consistofimportantsystemconfigurationfilesthatareavailablein/etcandthisdirectoryalsoconsistofdatasaresomewhatsimilartothecontrolpanelpresentinthewindowoperatingsystem./home-Itcontainssomeofthehomedirectoriesofthecommonusers./initrd-Itprovidesinformationforbooting./lib-ThisconsistsofLibraryfiles,includingthefilesforallkindsofprogramsneededbythesystemandalsobytheusers.

    Linuxfiletree

    /lost+found-Ineverypartitionhasalostandfoundinitsupperdirectoryand

  • thereforefilesthatweresavedwhenthefailureoccursarestoredhere./misc-Usedforvariousmiscellaneouspurposes./mnt-Thestandardmountpointfortheexternalfilesystems./net-Thestandardmountpointfortheentireremotefilesystemsisavailablehere./opt-Thiscontainsextraandthirdpartysoftware./root-Containingdataofthatoftheadministrativeusershomedirectoryandthereforeifmindthedifferencebetween/rootthehomedirectoryoftherootuser.

    Linuxtrafficcontrol

    IflowerPRIOclasscontainsnothingthenhighernumberedPRIOclassesareprocessed.Inorderofimportance3PRIOclassesareused.NoQdiscsarefilteredonlyplacetrafficintoclasses.TBFareratelimiting.HFBcanbeusedforratelimiting.

    Representationtable

  • CommandlineConfiguringLinuxbyusingcommandlineutilizesthemostpopularandmostpreferredway.IfeverusedLinuxforpersonalorprofessionalworkwouldhavedefinitelyusedthecommandline.

    Example

    $ls-a

    ..dmrcgoogleMemory_layout.jpgPictures.pulse-cookie

    .tmp_versions

    ..Documents.gstreamer-0.10modules.orderpractice

    .recently-used.xbeltry.c

    aDownloads.gtk-bookmarksModule.symversproc.c.recently-used.xbel.W69Q8VUnsavedDocument1

    a1.dropbox.gvfs.mozillaprocEntry123~.SkypeVideos

    .adobeDropbox.ICEauthority.mozilla-thunderbirdprocEntry12z~.ssh.vim

    alpha.dropbox-dist.icons.mplayerproc.ko.sudo_as_admin_successful.viminfo

    article_function_pointer.txt.esd_auth.javaMusic.proc.ko.cmd.teamviewervlc

    .bash_history.fontconfig.kchmviewermydataproc.mod.ctemplate.htmlworm

    .bash_logout.gconf.kdemy_lsproc.mod.oTemplates.xchat2

    .cache.gconfd.lesshstmy_ls_alpha.c.proc.mod.o.cmdtestdisk.log.xchm

    chmodOctal.txt.gegl-0.0libavmy_ls.cproc.otestfile.xsession-errors

    .compiz.gimp-2.6.linuxmint.nautilus.proc.o.cmdtest.py

    .xsession-errors.old

    .config.gksu.lock.local.openoffice.org.profile.themes

  • .dbus.gnome2.macromediaoutput.logPublic.thumbnails

    Desktop.gnome2_privateMakefilepics.pulse.thunderbird

    Parsingcommandlineargument

    Afterpassingthecommandlineargumentsthataremadeavailableinthecodethroughtheargcandargvargumentsofthismain()function.Thenextstepistoparsetheoptionsthenrunthecodeaccordingtoinputthatisprovidedbytheuserthroughtheprovidedflags.

    Example

    #include

    #include

    #include

    #defineCMP_LENGTH3

    enumop{

    ADD,

    SUB,

    MUL,

    DIV

    };

    intmain(intargc,char*argv[])

    {

    if(argc