Learn Ansi c

Embed Size (px)

Citation preview

  • 8/8/2019 Learn Ansi c

    1/31

    Ansi C Tutorial1 - Where do I start

    ============================ Aliens C Tutorial ================================-----------------Written by Alien [email protected]===============================================================================First of all, this tutorial will be much more of a challange to write

    then my previous tutorial (bash.tutor), in this tutorial I will tryto explain the C programming language and make it undestandeble.....This tutorial will explain ANSI C,(ANSI is American National Standards Institute).C was first developed at Bell Labs by Brian W. Kernighan and Dennis M. Ritchie.C is a programming language that needs to be compiled when written, thisis the oposit of shell scripting like bash.C is ALOT more powerful then bash or any script language, with C youhave real controll over what your program will do.C is developed for UNIX, and the examples in this tutorial is made towork on UNIX, they should however also work in DOS, but I leav nopromices for that.

    The code in this tutorial is written more or less only in K&R(Kernighan and Ritchie) style C, this style is also called Bell Labs style.Later I will explain the difference between the Bell Labs style andstudent style.I will not take up anything about graphical programming in this tutorialfor more then one reason, but the best is that it would take up to muchspace and be confusing, so if you want to learn graphical programming inC, read this tutorial to learn the actual language and then some othertutorial about graphical programming, another reason is that there ismore then one way of doing graphical programming because there areseveral sets of 'wigets' and libs that can do that.I will try to start from the very beginning so here we go.

    ===============================================================================1 - Where do I start ?===============================================================================You start here, with a simple "hello world" program.Make a file called hello.c and in it do the following://----------------------------------------------------------#include int main ( void ){printf ( "hello world!\n" );return 0;}

    //----------------------------------------------------------And once you've saved and exited, your ready to compile it,and that you do like this:gcc -o hello hello.cNow you can execute it:./helloAnd it will look like this:alien:~$ gcc -o hello hello.calien:~$ ./hellohello world!alien:~$-------------------------------------------------------------------------------So, now what have you done, and what does that mean ?

    You have done your first program in C, that will output "hello world!"to the screen.So, now 'exactly' what does the code mean ?

  • 8/8/2019 Learn Ansi c

    2/31

    Let's start from the first line.#include This will include the header file stdio (standard input output), this fileholds the information on how, among others, the printf function works andhow it should be handeld by the compiler.I will explain header files better later.The next after that is:

    int main ( void )This makes a function called main, which is the core function of your codethat can call for other functions later.main is always of type 'int' (integer), because it has to 'return' something tothe system, I will come to that very shortly.And the ( void ) part means that we will not pass any arguments to the mainfunction.You dont really have to know what all this means at this point, but I'm stilltelling it so you will have an easyer time understanding it later.The next line after that is the:

    {

    This opens the function, and expects an action.The next line after that is:printf ( "hello world!\n" );This is the main action in our program.Here we print 'hello world!' to the screen, the \n means new line.printf is a function, and as any funtion it's arguments is written insidethe paranteses, and the line is ended/terminated with a semi-colo.The next line is:return 0;Here we return 0 to the system, this means success, and the program know'sthat it has finished successfully here.0 means successful, and -1 means unsuccessful.And the last line:

    }This closes your function.-------------------------------------------------------------------------------Note: return 0; can also be written as: return ( 0 );-------------------------------------------------------------------------------So what do you need to remember about this at this point ?Well, the thing that you need to remember is the basic layout for aprogram.

    #include int main ( void ){return 0;

    }

    So memorize that for the time beeing.-------------------------------------------------------------------------------So next up ?Now it's time to explain integers and how to count in C, so here we go.Make a file called count.c and in it do the following://----------------------------------------------------------#include int main ( void ){int i, x;

    i = ( 50 );x = ( i + 10 );printf ( "x is now: %i \n", x );

  • 8/8/2019 Learn Ansi c

    3/31

    return 0;}//----------------------------------------------------------And once you've saved and exited, your ready to compile it,and that you do like this:gcc -o count count.cAnd now you can execute it by doing:

    ./countAnd it will look like this:alien:~$ gcc -o count count.calien:~$ ./countx is now: 60alien:~$-------------------------------------------------------------------------------So, now what have we done this time, and what does that mean ?The 3 first lines is (I hope) already well explained.So the fist new line here is:int i, x;This tells the program that there is 2 variables (separated by a comma),

    that are of type integer, all pointers and variables must be declaredbefore any real action in the code.Exactly what a pointer is I will explain after the next example.A variable is just a name that can hold data inside it ...That's not the best explanation, but that's a good way of thinking about it.It really works about the same a pointer, but just think of it as asynonyme or a rename of a value.These 2 integer variables can hold data that is integer numbers.Which is shown in the next line:i = ( 50 );Here we make the integer variable i hold the value 50.And the next line:x = ( i + 10 );

    Here we make the int x hold the value of i (50) plus 10, whichis 60.The next line after that we print the resault out to the screen:printf ( "x is now: %i \n", x );The new things here is the %i which tells printf to replace that spacewith an integer that's held in a variable that comes after the a commaafter the double quote, this will be shown better in later examples.And the return 0; and the close bracket is already explained.-------------------------------------------------------------------------------Next up is almost the same as the previous example, but this time withcharacters instead of integers.So here we go with an example of character pointers.Make a file called string.c and in it do the following://----------------------------------------------------------#include int main ( void ){char ptr[10];sprintf ( ptr, "My String" );printf ( "ptr contains: %s \n", ptr );return 0;}//----------------------------------------------------------

    And once you've saved and exited, your ready to compile it,

    and that you do like this:gcc -o string string.cAnd now you can execute it by doing:

  • 8/8/2019 Learn Ansi c

    4/31

    ./stringAnd it will look like this:alien:~$ gcc -o string string.calien:~$ ./stringptr contains: My Stringalien:~$-------------------------------------------------------------------------------

    So, now what have we done now, and what does that mean ?As before the first 3 lines you should know now.And then there is the next new line that looks like this:char ptr[10];This declares a pointer that will hold data of type char (characters),and the [10], means that it will hold the room for max 10 characters.The next new line in the code is this:sprintf ( ptr, "My String" );sprintf means string print file, and the pointer is before the static text,because this time we are pointing the pointer to a string and not displayingit like to the screen like we did with the integers in the last example.In short, sprintf will point a point 'to' the string.

    (pointers will be explaind under this example).But that we do here instead:printf ( "ptr contains: %s \n", ptr );This works the same as with the integers but we have to use %s to tellprintf that it's suppose to write it out as characters.And the 2 last lines you should know by now.-------------------------------------------------------------------------------So exactly what is a pointer ?I will try to be breaf about this, and you dont really need to remember this,I'm putting it here for the sake of the knowlidge and that you should atleasthave read it at some time .... so now is a time as good as any.Here we have a chunk of memory in the computer:1 2 3 4 5 6 7 8 9 10 11 12

    ------------------------------------------------- -------------------------------------------------This is a chunk of memory that has 12 bytes.And if we do:char pointer[6];It will resault in this:1 2 3 4 5 6 7 8 9 10 11 12

    ------------------------------------------------- -------------------------------------------------^ ^_____________________------ pointerSo you see, that's why it's called a pointer, because it points to achunk of memory, and if we write something to it, by doing say:sprintf ( pointer, "String" );The memory will look like this:1 2 3 4 5 6 7 8 9 10 11 12

    ------------------------------------------------- S t r i n g -------------------------------------------------^ ^_______________________

    ------ pointerThis is why you need to declare a pointer, so it can point to a free space

  • 8/8/2019 Learn Ansi c

    5/31

    in the memory, of the size of your choice, where it can store it's data.I hope that this explains how a pointer works.-------------------------------------------------------------------------------Here is an example with both characters and integers.Make a file called intstring.c and in it do the following://----------------------------------------------------------#include

    int main ( void ){int i, j, x;char ptr[10];sprintf ( ptr, "My String" );

    i = ( 3 );j = ( 7 );x = ( i + j );printf ( "ptr contains: %s \nAnd x contains: %i \n", ptr, x );return 0;}//----------------------------------------------------------

    And once you've saved and exited, your ready to compile it etc.And it will look like this:alien:~$ gcc -o intstring intstring.calien:~$ ./intstringptr contains: My StringAnd x contains: 10alien:~$-------------------------------------------------------------------------------This time you should know what we have done.But just in case, I'll explain it anyway.First we inlude the standard input/output header file.Then we create a main function with nothing to pass to it, (the void).Then we open the function.

    After that we declare i, j and x as integers.And then declare ptr as a char pointer that may hold 10 bytes.After that we print "My String" to the memory location of the ptr pointer.Next we say that i should be a 3, j a 7 and x should hold i + j,which means 3 + 7.And then we print it out to the screen.If you look at the line where we print it out to the screen:printf ( "ptr contains: %s \nAnd x contains: %i \n", ptr, x );Now if we were to print out the integer first and the string after that,the line would have looked like this:printf ( "x contains: %i \nAnd ptr contains: %s \n", x, ptr );Notice that you also have to switch places for the pointers after thedouble quote.After that we have the return 0; which tells the system that it's come tothis point successfully and that it will quit here.And then we close the main function.-------------------------------------------------------------------------------Note: printf with pointers works like this:printf ("char 1 %s - char 2 %s - char 3 %s etc.", char1, char2, char 3);-------------------------------------------------------------------------------Now it's time to start to comment the code.To make memory notes so you know what you have done for later.This is something all coders does.Let's take the last code, intstring.c and comment it.//----------------------------------------------------------

    #include int main ( void ){

  • 8/8/2019 Learn Ansi c

    6/31

    /* declare variables and pointers */int i, j, x;

    char ptr[10];/* print the string to the memory location

    * that the pointer ptr points to.*/sprintf ( ptr, "My String" );

    /* point the integers to something */i = ( 3 );

    j = ( 7 );x = ( i + j );/* print it out to the screen */printf ( "ptr contains: %s \nAnd x contains: %i \n", ptr, x );/* return success and exit. */return 0;

    }//----------------------------------------------------------Now normally you dont comment *everything* in a code like this,but you may wanna comment things in your codes so that you can remember

    what you have done and to make it easyer to search, and if not for that,to make it readeble to others, if you are in a coding team.The /* starts a comment and */ ends a comment in C, and if you have severallines you do like this:/* here is* a comment* that's* severa lines*/You may also come across comments that are made with 2 slashes like this: //That is really a C++ comment and will comment out the rest of the linefrom that point.It can be used like this:

    printf ( "Anything here\n"); // print something to the screenBut a real C comment should look like this:printf ( "Anything here\n"); /* print something to the screen */Note that they both work in C and C++, but it's standard to use the /**/ in Cand the // in C++.-------------------------------------------------------------------------------That was the very start to begin to learn C, this following sectionwill be a little bit harder, but still basics.Share This Posted in Ansi C Tutorial 2 Comments July 11th, 20072 - Basic C programming

    ===============================================================================2 - Basic C programming.===============================================================================Now when you know how a pointer works, what an int is, and you can usesprintf and printf, it's time to move on to the next step.The things I will take up first here is the if and else statement in C,the for loop and the scanf function.And then the argument vectors and argument count (argv and argc), andalso strcpm, strcpy and atoi.So here we go with the if statement.-------------------------------------------------------------------------------The if statement works like this:if ( condition ) { action } else { other-action }

    Let me demonstrate this in a code, make a file called ifstate.c and in it do://----------------------------------------------------------#include

  • 8/8/2019 Learn Ansi c

    7/31

    int main ( void ){int i;

    i = ( 1 );if ( i == 1 ) {printf ( "i is 1\n" );

    }else{printf ( "i isnt 1\n" );}return 0;}//----------------------------------------------------------Here we have it:if ( condition ) { action } else { other-action }The condition is i == 1, so if i is 1 (which it is from "i = ( 1 );"), thenit will perform the action which is to print "i is 1" to the screen,

    else it will perform the other-action which is to print "i isnt 1" tothe screen.If you in this code change the "i = ( 1 );" to "i = ( 2 );", then itwill print the other-action instead of the action.This will look like this executed:alien:~$ gcc -o ifstate ifstate.calien:~$ ./ifstatei is 1alien:~$-------------------------------------------------------------------------------So why do we do == in the if and not only = ?C uses the boolean operators, which is as follows:-------------------------------------------------------------------------------

    == equal to.!= not equal to.= or equal to.> greather then.>= greather then or equal to.< less then.

  • 8/8/2019 Learn Ansi c

    8/31

    So what does this do ?First we declare integers, i and x, and then we make i = 10 + 10 whichneedless to say is 20, and then we make x = i, so that x is now 20.Then we say, if x is less then 50 (which it is), then it prints outx is 20 (since x is i which is 20), else it will print outx is .Not so very hard is it ?

    -------------------------------------------------------------------------------Now it's time to take a look at the for loop.The first thing I need to say here is that i++ will increas i with 1,let me illustrate this in a tiny code://----------------------------------------------------------#include int main ( void ){int i;i = ( 2 );printf ("i is now %i\n", i);i++;

    printf ("i is now %i\n", i);i++;printf ("i is now %i\n", i);return 0;}//----------------------------------------------------------This will output the following:i is now 2i is now 3i is now 4This is very handy, I should also say that i--; will decrease i by 1.But now on to an example with a for loop, make a file and call it forloop.cand in it do the following:

    //----------------------------------------------------------#include int main ( void ){int i;

    for ( i = 0 ; i < 10 ; i++ ) {printf ( "i is now: %i\n", i );}return 0;}//----------------------------------------------------------Let's see how this looks when it's executed.alien:~$ gcc -o forloop forloop.calien:~$ ./forloopi is now: 0i is now: 1i is now: 2i is now: 3i is now: 4i is now: 5i is now: 6i is now: 7i is now: 8i is now: 9

    alien:~$-------------------------------------------------------------------------------So now what does the code mean ?

  • 8/8/2019 Learn Ansi c

    9/31

    First for works like this:for ( ; condition ; ) { action }So let's cut right to the new part:....for ( i = 0 ; i < 10 ; i++ ) {printf ( "i is now: %i\n", i );}

    ....First let's take a look at what's inside the paranteses.Three feilds separated by ; (semi colon)"i = 0 ; i < 10 ; i++"."i = 0", that's easy to know what it means. it set's i to be 0.The next of the 3 feilds is "i < 10", this means that as long asi is less then 10, it will perform the action.And then the "i++" that will increase "i" for every time it loops.So basically it will read what's inside paranteses over and over againuntil it the condition is reached, each time performing the action.In this code the condition will be met when i is no longer less then 10.-------------------------------------------------------------------------------

    Now here is another short example of a for loop, this time without thesurrounding code.....for (;;) {printf ("This will go on forver\n");}....I dont even need to explain this very much.If you dont set any conditions at all, it will just keep on loopingfor all eternety.This can be very useful at times, like when coding daemons (servers)that are suppose to do something over and over again all of the time.-------------------------------------------------------------------------------

    Now let's take a look at the scanf function.scanf() is a function that will take something from stdin(standard input - the keyboard), and use it in the code.Let's illustrate it in an example.Make a file called say scanftest.c and in it do this://----------------------------------------------------------#include int main ( void ){char str[50];printf ( "Type something: " );scanf ( "%s", &str );printf ( "You typed %s \n", str );return 0;}//----------------------------------------------------------Ok, so what does the new stuff here really do ?First we create a pointer that we call str that can hold 50 characters.The we print to screen (stdout - standard output) "Type something: ",and after that we use scanf().scanf ( "%s", &str );This means that it scans %s (characters), and writes's them to str.So why is there an amplersand (&) before the str ?This is called to refference a pointer, you do that when you're writingsomething to the actual location of where the pointer points to.

    I will come back to that more later, for now just remember that thisis one of the places where you need to have an & before the pointer.And then we print it out.

  • 8/8/2019 Learn Ansi c

    10/31

    So, executed it could look like this:alien:~$ gcc -o scanftest scanftest.calien:~$ ./scanftestType something: testYou typed testalien:~$-------------------------------------------------------------------------------

    And that's all you need to know about the scanf function for now.-------------------------------------------------------------------------------Now let's take a look at argc and argv.argc means argument counter and is an int, it will hold the number of argumentspassed on to the program. ( 3 arguments to a program is this ./program -o foo )know that the program name it self is an argument in the 'mind' of argc.arg means argument vector is is a char, and it will hold the actualarguments passed to the program from the execution line.So, in order to make this work, I said earlyer that the void in"int main (void)" was there because we didnt pass anything on to the function,but now we will, so here is an example, let's call the file program1.c://----------------------------------------------------------

    #include int main ( int argc, char **argv ){if ( argc != 2 ) {fprintf ( stderr, "Wrong number of arguments.\n" );return -1;}printf ( "The argument was %s \n", argv[1] );return 0;}//----------------------------------------------------------Here are a few new things.First:

    int main ( int argc, char **argv )This means that it will import argc as an int, argc was just explained.and then we have argv as a char.So why is there 2 *'s infront of argv ?Well here a * infront of it means the same as a [] after it, some peoplewrite it as "char *argv[]" personally I think that looks weird.But perhaps the second way is more 'correct'.Anyway, this means that argv[0], is argument 0, and hence the program name.And argv[1], the first argument after the program name... and argv[2]beeing the argument after that etc.Then we have:if ( argc != 2 ) {This simply means, "if the argument counter not is two, then do .....".And what does it do ?This is also new.fprintf ( stderr, "Wrong number of arguments.\n" );fprintf means file print file, and the file that we are printing the messageto is stderr (/dev/stderr).stderr is an abbreviation for standard error, with normal printf you printby default to stdout which means standard output, and with scanf you readfrom stdin, which is standard input... see the note below.And why are you writing it out as stderr ?One of the reasons is that if someone writes a shell script where your programis called, they may expect errors and dont want them visible, and so they canredirect the errors to /dev/null (the black hole of UNIX), but still see the

    stdout if any appears.And the next two lines after that:return -1;

  • 8/8/2019 Learn Ansi c

    11/31

    }-1 means that it will return unsuccessful and quit.Again one of the reasons for doing this is if somone does a shell scriptthat needs to know if the program was executed successfully or not.And then close the if statement with the bracket.And the next line .... you should be able to figure that one out:printf ( "The argument was %s \n", argv[1] );

    The normal printf you know, and the %s you know too by now.But instead of a 'normal' pointer we use argv[1], argv is a pointer toall the arguments, and the number inside the brackets says which of thearguments it should be.And then return with success and close the main function.So basically, if it has the wrong number of arguments it will die andtell you so, but in other cases it will ignore the action of the if statementbecause the condition isn't met... and go right on to the printf line.So, executed it could look like this:alien:~$ gcc -o program1 program1.calien:~$ ./program1Wrong number of arguments.

    alien:~$Or:alien:~$ gcc -o program1 program1.calien:~$ ./program1 fooThe argument was fooalien:~$Or:alien:~$ gcc -o program1 program1.calien:~$ ./program1 barThe argument was baralien:~$etc.-------------------------------------------------------------------------------

    I/O (Input / Output)stdout - standard output (1)stderr - standard error (2)stdin - standard input-------------------------------------------------------------------------------Now let's take a short look at the strcmp function.strcmp means string compare, and will compare two character strings,(just two pointers works just as well, but here we will compare a pointerwith a pre made string).So let's begin, open a file and call it strcmpex.c, and in it do://----------------------------------------------------------#include int main ( int argc, char **argv ){if ( argc != 2 ) {fprintf ( stderr, "Wrong number of arguments.\n" );return -1;}if ( strcmp ( argv[1], "root" ) == 0 ) {printf ( "argv[1] was root\n" );}else{printf ( "argv[1] was NOT root\n" );}

    return 0;}//----------------------------------------------------------

  • 8/8/2019 Learn Ansi c

    12/31

    Now the only really new thing in here was this line:if ( strcmp ( argv[1], "root" ) == 0 ) {This will compare if argv[1] (the first argument after the program name),and the word/string "root" returns success (that will only happen if theyare the same), and if so do the action.If we instead would have said:if ( strcmp ( argv[1], "root" ) != 0 ) {

    That would have meant, if argv[1] and "root" does not match....This should be understandeble, but just in case it isn't, there will bebe another explanation with an example shortly.This time I will not show how this program looks executed, you gonna haveto test it your self, unless you already can deduct how it will look.-------------------------------------------------------------------------------So now let's take a short look at the atoi (ascii to integer).atoi is really simple, and works like this:....int i;char str[3];sprintf ( str "5" );

    i = ( atoi ( str ) );....And as you see, now the char that contains "5" as a character, is nowconverted to an integer.This will come to good use in a while.Basicly, you could say that "atoi(str)" is used the same way as ifthe char would have been a single int in the first place.There is also atof (ascii to float) and atol (ascii to long) etc. but I'llexplain those later.-------------------------------------------------------------------------------Now let's make a little test program, just to see how a program that actuallyhas a purpose and makes use of what you know this far looks like.So as a test example let's do a little very simple calculator.

    So open a file, let's call it calc.c and in it type the following://----------------------------------------------------------#include int main ( int argc, char **argv ){int i;if ( argc != 4 ) {fprintf ( stderr, "Usage: %s \n", argv[0]);return -1;}if ( strcmp ( argv[2], "+" ) == 0 ) {i = ( atoi ( argv[1] ) + atoi ( argv[3] ) );}if ( strcmp ( argv[2], "-" ) == 0 ) {i = ( atoi ( argv[1] ) - atoi ( argv[3] ) );}if ( strcmp ( argv[2], "/" ) == 0 ) {i = ( atoi ( argv[1] ) / atoi ( argv[3] ) );}if ( strcmp ( argv[2], "*" ) == 0 ) {i = ( atoi ( argv[1] ) * atoi ( argv[3] ) );}printf ( "The answer is: %i \n", i );return 0;}

    //----------------------------------------------------------Now let's see what we have done here:Everything should be understandeble and clear, but just in case

  • 8/8/2019 Learn Ansi c

    13/31

    you dont follow this to 100% I'll explain it again in detail.First we include the standard input output header file.#include Then we make a main function that may import the numbers of arguments asan integer (int argc - argument counter), and the arguments them selfas characters / ascii, (char **argv - argument vector).int main ( int argc, char **argv )

    The we open the funciton with a bracket.{Then we declare i as an integer.int i;Then we ask if the argument counter is not 4.if ( argc != 4 ) {And if it's not 4 arguments (the program name is one of them),then we print the following to stderr (the standard error output).fprintf ( stderr, "Usage: %s \n", argv[0]);And after that we exit the program with status - unsuccessful.return -1;And then we close the "if" function.

    }And if the "if" function didnt exit us which it only happens if the argcis others then 4, then the program goes on to the following.Here we check if argv[2] is a "+".if ( strcmp ( argv[2], "+" ) == 0 ) {And if it is a plus, then it will count argv[1] + argv[3] (the argv's getsconverted to intgers with the atoi).i = ( atoi ( argv[1] ) + atoi ( argv[3] ) );And then we close that if function.}Next we check if argv[2] is a "-".if ( strcmp ( argv[2], "-" ) == 0 ) {And if it is a minus, then it will count argv[1] - argv[3].

    i = ( atoi ( argv[1] ) - atoi ( argv[3] ) );And then we close that if function.}Next we check if argv[2] is a "/".if ( strcmp ( argv[2], "/" ) == 0 ) {And if it is a slash (devided with), then it will count argv[1] / argv[3].i = ( atoi ( argv[1] ) / atoi ( argv[3] ) );And then we close that if function.}And last we check if argv[2] is a "*".if ( strcmp ( argv[2], "*" ) == 0 ) {And if it is a asterisk (times), then it will count argv[1] * argv[3].i = ( atoi ( argv[1] ) * atoi ( argv[3] ) );And then we close that if function.}After having the actual counting done, we print it out.printf ( "The answer is: %i \n", i );And then we exit with success.return 0;And finally we close the main funtion.}-------------------------------------------------------------------------------The compiling:alien:~$ gcc -o calc calc.cThis executed may look like this:

    alien:~$ ./calc 12 + 23The answer is: 35alien:~$

  • 8/8/2019 Learn Ansi c

    14/31

    Or:alien:~$ ./calc 15 - 9The answer is: 6alien:~$Or:alien:~$ ./calc 44 / 3The answer is: 14

    alien:~$Or:alien:~$ ./calc 9 '*' 8The answer is: 72alien:~$Note that the asterisk have to be within ` quotes, else it will expand asa wildcard, and so wont work.-------------------------------------------------------------------------------Finally in this section, let's have a look at the strcpy() function.strcpy() works a little like sprintf, to say:strcpy( ptr, argv[0] );Is the same as to say:

    sprintf ( ptr, "%s", argv[0] );So strcpy(), will copy the second character pointer to the first one.Let's make a short example://----------------------------------------------------------#include int main ( int argc, char **argv ){char ptr[256];

    strcpy ( ptr, argv[0] );printf ( "The program name of this program is: %s \n" , ptr );return 0;}

    //----------------------------------------------------------Now try this, and you'll understand it if you dont undersand it already.-------------------------------------------------------------------------------That was about all on the very first basics on C programming, at this pointyou should play some and make silly little program that dont have anyreal purpose, unless you have some great ideas.Share This Posted in Ansi C Tutorial 2 Comments July 11th, 20073 - A little more advanced basics

    ===============================================================================3 - A little more advanced basics.===============================================================================Here we will look at the basics of dynamic memory allocation, functions,struct, typedef, define and some other new things.So let's not waste time on weird elaborations of nothing, here we go withthe simple basics of dynamic memory allocation:-------------------------------------------------------------------------------As I've mentiond, to create a char pointer you need to allocate space for it,like this:char ptr[10];That is a char pointer named ptr that can hold 10 bytes, or 80 bits (there's 8bits in one byte), but the downside of that is that you have to know how muchmemory it will use... and sometimes you dont know that.So here is where the malloc() function comes handy, malloc means

    memory allocation or memory allocate.So first thing we need to create a pointer that has no memory allocated, thatwe do like this:

  • 8/8/2019 Learn Ansi c

    15/31

    char *ptr;This would be the same as to say:char ptr[];Since a [] at the end means the same as a * in the beginning when youdeclare pointers.But *ptr; looks better.The next thing you need is to allocate the memory to it dynamicly, that

    you do something like this:ptr = (char *) malloc ( strlen ( str ) );Now what does that mean ?First, the pointer equals the rest of the line, and the rest of the linemeans, first we have (char *) which is called a cast.A cast tells the program what sort of memory it should alocate, if it'sa void if it's an int or if it's a char or any other data type.The next thing is the malloc( strlen(str) );, that means that it willallocate the same amount of bytes as the str pointer is long.Now that may seem confusing at this point since the pointer containsnothing yet, but at the time it compiles the compiler will look at the wholething and see how long it will be.

    A note is that the strlen() is a new thing here, let's make a simpleexample of the strlen() function so you understand it (strlen needs string.h)://----------------------------------------------------------#include #include int main ( int argc, char **argv ){int i;i = ( strlen ( argv[1] ) );printf ( "The first argument was %i characters long.\n", i );return 0;}//----------------------------------------------------------

    Now, that should be understandeble, and if it isn't, try it.(A note is that the program will 'segmentaion fault' if you dontsupply any arguments, this means that it will try to read memory that'snot there... to fix that you can add an "if ( argc != ..... etc.").

    So, now we should be ready to make a little example program withdynamic memory allocation, let's call the file program2.c//----------------------------------------------------------#include #include int main ( int argc, char **argv ){int i;char *ptr;if ( argc != 2 ) {

    fprintf ( stderr, "Usage: %s \n", argv[0]);return -1;}i = ( strlen ( argv[1] ) );

    ptr = (char *) malloc ( i + 10 );strcpy ( ptr, argv[1] );

    printf ( "The argument was: %s and that is %i characters long.\n", ptr, i );return 0;}

    //----------------------------------------------------------Now let's take a look at what we have done here.First we include the stdio.h header file.

  • 8/8/2019 Learn Ansi c

    16/31

  • 8/8/2019 Learn Ansi c

    17/31

    //----------------------------------------------------------#include int main ( void ){typedef struct mystruct my_struct;struct mystruct {char buffer[20];

    };my_struct *one;sprintf ( one->buffer, "something" );

    printf ( "%s\n", one->buffer );return ( 0 );}//----------------------------------------------------------So what does this mean ?Let's go right to the new part again:.....typedef struct mystruct my_struct;struct mystruct {

    char buffer[20];};my_struct *one;

    .....typedef sorta renames "struct mystruct" to "my_struct", you need to do thisso you can declare "one" as a pointer to the struct function "my_struct *one;".This means that you use "one->buffer" instead of "one.buffer" to pointto the member of the struct.This will come to use later.-------------------------------------------------------------------------------Now let's take a short look at define, here is an example://----------------------------------------------------------#include

    #define ONE 1int main ( void ){printf ( "%i\n", ONE );return 0;}//----------------------------------------------------------As you can see this is really simple, you just define "ONE" as "1",you can say:#define USA 01#define SWE 46#define AUS 61Or whatever ..... and so the USA, SWE and AUS can be used as variables inthe code.-------------------------------------------------------------------------------Now let's take a look at functions, to this point we have only made onemain function in each program, but let's change that.Actually the main function in a program should be as short as possible,and only used to call for the other functions.So let's make an example of a little program with more then one function.Let's call the file program3.c//----------------------------------------------------------#include int usage ( int i, char *myname );int main ( int argc, char **argv )

    {usage ( argc, argv[0] );printf ( "The argument was %s\n", argv[1] );

  • 8/8/2019 Learn Ansi c

    18/31

    return 0;}int usage ( int i, char *myname ){if ( i != 2 ) {fprintf ( stderr, "Usage: %s \n", myname);return -1;

    }}//----------------------------------------------------------So now what does this mean, and why ?First we inclide the standard input output header file as usual.The we do something new, we declare a funciton, this you do as here,simply by typing the full function name with what it may importand a semi colon ";" after it.Then we make a main function that may import the argument counter asan integer and the actual arguements as characters, where on we openthe main function.Then we call for the usage() function and export argc and argv[0] to it.

    And after it has performed that function it will print out the printf line,and then exit with success.Now the usage() function ......First we create it and import an integer and name it "i" and a char thatwe name myname, and then open the funtion.Then we ask if i (which was imported from argc and has argcs value),is anything else then 2, and if it is anything else then 2, thenit will display the usage and return with status unsuccessful.Note that the char myname will hold the value of argv[0].And then we close that function.-------------------------------------------------------------------------------This program executed looks like this:alien:~$ ./program3 foo

    The argument was fooalien:~$alien:~$ ./program3Usage: ./program3 alien:~$-------------------------------------------------------------------------------So now, what's the real point of functions ?A function is really designed to import something and return something else.This is the whole thing about a program with arguments aswell, soyou could say that a function is a program within the program.Another good point of functions is that when you have really big projectsthat are several thousen lines of code, then one file is to easy toloose over view of, so then you can make one file for each functionand use a Makefile to compile it, I will explain this later.Almost everything you use are functions, like printf is a functiondescribed with syntax and all in stdio.h, that's why you need header files,I will breafly explain header files and how to make them later.Functions are good to use, and even if you're making a small programyou should always make a habit of making separat functions, and call themfrom the main function.-------------------------------------------------------------------------------Here is another example with several functions, let's name the file functions.c//----------------------------------------------------------#include int usage ( int i, char *myname );

    void diplay1 ( char *argument );void diplay2 ( void );int main ( int argc, char **argv )

  • 8/8/2019 Learn Ansi c

    19/31

    {usage ( argc, argv[0] );diplay1( argv[1] );diplay2();return 0;}int usage ( int i, char *myname )

    {if ( i != 2 ) {fprintf ( stderr, "Usage: %s \n", myname);return -1;}}void diplay1 ( char *argument ){printf ( "Here is what's in diplay1() and argv[1] was: %s\n", argument );}void diplay2 ( void ){

    printf ( "Here is what's in diplay2()\n" );}//----------------------------------------------------------First we include the header file like always.Then we decalare the functions that we will use, (note that display 1 & 2are void, because they dont return anything to the system).Then we create a main function and open it.Then we call for the functions, usage(), and export argc and argv[0] to it.And then we call for diplay1(), and export argv[1] to that, and after thatwe call for diplay2() to which we export nothing.And then we return success and exit.The usage function is the same as before.Then we have the diplay1 function, which imports a char that we have named

    argument, which will contain argv[1] because that's what we exported to it.And what's in diplay1() should be understandeble, same goes for what's indiplay2().I will go deeper into what a function can return more then 0 or -1 in a while,when I take up Makefiles etc.At this point you should play around some with this and practice.This brings us to the next section:Share This Posted in Ansi C Tutorial No Comments July 11th, 20074 - Some theoretical C programming with more basics, Makefiles and styles.

    ===============================================================================4 - Some theoretical C programming with more basics, Makefiles and styles.===============================================================================This section will be quite short, here I'll explain how you should thinkwhen you make ideas for a program and the difference between the Bell Labs(K&R - Kerninghan and Ritche) style and student style.So let's start with how to plan and think when you do a program.-------------------------------------------------------------------------------If you plan at all when you make a program, and you should if you want itto work well, you should take a paper and a pen and draw what you want eachfunction to do, make each function as a little box and start, just freedream thinking, let me illustrate what I mean with an example:-------------------------------------------------------------------------------___________________________

    main function calls the other functions

  • 8/8/2019 Learn Ansi c

    20/31

    ___________________________ ______________________ usage function... ----------------------------- if ( argc != 2 ) {} return -1 if not. ______________________

    ______________________ funct1 should import ----------------------------- an argc and return that + itself -1 ___________________________________________

    funct2 should printf the resault of funct1 ______________________-------------------------------------------------------------------------------Here we have a number of boxes which each resembles a function, with littlenotes in them, now let's make the program that this example illustrates://----------------------------------------------------------#include #include void usage ( int i, char *myname );int funct1 ( int i );void funct2 ( int i );

    int main ( int argc, char **argv ){usage ( argc, argv[0] );funct2 ( funct1 ( argc ) );return 0;}void usage ( int i, char *myname ){if ( i != 2 ) {fprintf ( stderr, "Usage: %s \n", myname );return -1;}}int funct1 ( int i ){int x;x = ( i + i - 1 );return ( x );}void funct2 ( int i ){printf ( "The resault of argc + it self - 1 = %i\n", i );}//----------------------------------------------------------There are 4 new things in this code that I will explain before doing anything

    else, the new things are:#include This we include because we use the exit() function.

  • 8/8/2019 Learn Ansi c

    21/31

    This means that the exit() function with syntax is described in unistd.h.And then we have the:exit ( -1 );This means kill the program with status unsuccessful, exit doesn't returnanything.And then:funct2 ( funct1 ( argc ) );

    andreturn ( x );Now, funct1( argc ) will return something from it's "return ( x );", whichin this case is an integer, and so we can use "funct1( argc )" as an integer,so when we say "funct2 ( funct1 ( argc ) );" we use the output of"funct1( argc )" as the input to funct2().If you dont really understand it, read the code again and what I just said,and if you still dont understand it, dont worry, I'll explain it againlater.So now, if you read the source and compare it to the idea with the boxesyou'll come to the conclution that the boxes we drew are the same ideaas the program, just written in a human way instead of a computer way.

    This way of thinking is also called "modular thinking", that every functionis a part and you can add as many parts as you want as long as themain program allows them to integrate with it.When you start to think modular, it will be really easy to make and thinklike the functions, and it will make programming very much easyer.Don't just read this as text and then continue, make sure to put the examplecode in a file and compile it so you can try it, and play around with it, likerewriting some of the code just to see what happens.-------------------------------------------------------------------------------Now let's take a look on how to make a Makefile.Let's use our last program as an example, so let's cut it up in severalfiles (it's easyer if you make a dedicated directory for this):program1.h:

    //----------------------------------------------------------#include #include void usage ( int i, char *myname );int funct1 ( int i );void funct2 ( int i );//----------------------------------------------------------

    main.c//----------------------------------------------------------#include "program1.h"int main ( int argc, char **argv ){usage ( argc, argv[0] );funct2 ( funct1 ( argc ) );return 0;}//----------------------------------------------------------

    usage.c//----------------------------------------------------------#include "program1.h"void usage ( int i, char *myname ){if ( i != 2 ) {

    fprintf ( stderr, "Usage: %s \n", myname );exit ( -1 );}

  • 8/8/2019 Learn Ansi c

    22/31

    }//----------------------------------------------------------

    funct1.c//----------------------------------------------------------#include "program1.h"int funct1 ( int i )

    {int x;x = ( i + i - 1 );return ( x );}//----------------------------------------------------------

    funct2.c//----------------------------------------------------------#include "program1.h"void funct2 ( int i ){

    printf ( "The resault of argc + it self - 1 = %i\n", i );}//----------------------------------------------------------And then we make the Makefile://----------------------------------------------------------HDRS = program1.hOBJS = main.o usage.o funct1.o funct2.oSRCS = main.c usage.c funct1.c funct2.cCC = gcc -g -Wall -O3all: $(OBJS) program1main.o: $(HDRS) main.c$(CC) -c main.cusage.o: $(HDRS) usage.c

    $(CC) -c usage.cfunct1.o: $(HDRS) funct1.c$(CC) -c funct1.cfunct2.o: $(HDRS) funct2.c$(CC) -c funct2.cprogram1: $(OBJS)$(CC) main.o usage.o funct1.o funct2.o -o program1clean:rm -rf *.o core program1 *~//----------------------------------------------------------Now let me explain the Makefile.First, if there is more then 2 spaces in a row in the Makefile then it'sa TAB and not spaces.Now first in the Makefile we set the variables.HDRS, OBJS, SRCS and CC.HDRS is the header files to be included, and here we made our own, so thatwe can inclue it in every file, because the header file is in the same diras the source and not in any real include dir we have it enclosed byquotes "" instead of .Then we set OBJS, which is the object files that should be created from thesource..Then we set the SRCS, which is the source files, that is all the fileswe are going to compile.And then we set CC, which is the C Compiler with or without flags..You can set the flags separatly with "CFLAGS = -g -Wall -O3" or whatever

    flags you want and use them as "$(CC) $(CFLAGS)", but here we set theflags "-g -Wall -O3" in the CC, and just so you know, "-g" meansdebugging information, I'll explain this later, and "-Wall" means "Warn all"

  • 8/8/2019 Learn Ansi c

    23/31

    and it will warn about any error, even if it doesnt matter if it's there.And then we have "-O3" wich menans "Optimize 3 levels", this will optimizeyour bianry (compiled source - program).Then we have:"all" is the default action when you type "make" and it will run the program1'function' later in the Makefile.all: $(OBJS) program1

    This tells the compiler how to do the main.o (object) file.main.o: $(HDRS) main.c$(CC) -c main.cThis tells the compiler how to do the usage.o file.usage.o: $(HDRS) usage.c$(CC) -c usage.cAnd the same for funct1 and funct2 ......And here is the program1 'function'.This will link the object files to a binary program named "program1",this Makefile is made so that if it dont find an object file at this pointit will make it from the source.program1: $(OBJS)

    $(CC) main.o usage.o funct1.o funct2.o -o program1

    And finally the clean 'function', so if you type "make clean" it willremove all object files, any core file etc.clean:rm -rf *.o core program1 *~-------------------------------------------------------------------------------That was is a recursive Makefile ....The same Makefile but not recursive would look like this://----------------------------------------------------------CC = gcc -g -Wall -O3all: program1program1:

    $(CC) -c main.c$(CC) -c usage.c$(CC) -c funct1.c$(CC) -c funct2.c$(CC) main.o usage.o funct1.o funct2.o -o program1clean:rm -rf *.o core program1 *~//----------------------------------------------------------It's about the same thing, but it wont act as 'modular' as the recursive one.-------------------------------------------------------------------------------Now let's take a look at styles in C, I've already said that my examples hereare in K&R / Bell Labs style, but there is also student style, let's make ashort example first one in Bell Labs style and then the same in student style.Bell Labs style://----------------------------------------------------------#include int main ( int argc, char **argv ){if ( argc != 2 ) {fprintf ( stderr, "Usage: %s \n", argv[0]);return -1;}printf ( "The argument was %s\n", argv[1] );

    return 0;}

    //----------------------------------------------------------

    Student style:

  • 8/8/2019 Learn Ansi c

    24/31

    //----------------------------------------------------------#include int main(int argc,char **argv){if(argc!=2){fprintf(stderr,"Usage: %s \n",argv[0]);return -1;}printf("The argument was %s\n",argv[1]);

    return 0;}//----------------------------------------------------------Now as you can see, Bell Labs style is much cleaner and much easyer to read.So what is the actual difference ?Well, a Bell Labs style function looks like this:function ( ) {action;}While a Student style function looks like this:function(){action;}Bell Labs style has the opening { on the same line as the functionand the closing } on a line by it self, with the action inbetween.

    And then Bell Labs style has alot of spaces and *air* in the codeto make it easy to read for your self and others if you're in acoding team.All professional programmers I've seen this far uses Bell Labs style.Let's not go deeper into the difference of the styles, just know thatthere are different styles so you dont get confused if you see codes thatlook really bizzare and *home made*.-------------------------------------------------------------------------------So now on to some more new stuff in C, to make it even easyer, to do somestuff.I've said that "strlen ( pointer )" will return the string length of thepointer as an integer, but there is another one just like that.sizeof ( pointer );

    This will return the bit size of a pointer, so say that a pointer containsthe string "1234", strlen will return 4, since it's 4 bytes long, whilesizeof will return 16 since 4 * 8 == 16 ( there is 8 bits for 1 byte ).I've also talked about strcmp() and strcpy(), now I wanna say that thereis 2 more, just like those but that's more *secure*, strncmp and strncpy.The difference is that strncmp and strncpy wants the strlen of the string too.Let me show you:strcpy ( ptr, "string" );strncpy ( ptr, "string", 6 );strncmp ( ptr, "string" );strncmp ( ptr, "string", 6 );Now this is really easy once we know about strlen().Like this:strncmp ( ptr, argv[1], strlen ( argv[1] ) );See ?Another thing is the write() function, it works almost as fprintf, butit wants the strlen, let me show you:write ( 0, argv[1], strlen ( argv[1] ) );This will have the same effect as doing either:printf ( "%s", argv[1] );or rather:fprintf ( stdout, "%s", argv[1] );the 0 in write() is a file descriptor, 0 means none or default which isstdout, but you can write to a file if you've opend it (I'll show you thatsoon), or a socket (I'll take up that too) etc.

    there is alot of those small functions, like:strchr()memmem()

  • 8/8/2019 Learn Ansi c

    25/31

    strcat()memcpy()memcmp()calloc()realloc()stat()fstat()

    fseek()atol()strtod()strtol()strtoul()And so on for a good while .... It's pretty pointless trying to learnall of them at once .... and this is a tutorial not a library refference.So I will not go over all functions in the whole language, if you wannalearn all functions there is, get a book or find some place onlinethat has them all.This tutorial will have enough to teach you the actual language wellenough so you can make your own programs at need, and so that you

    without problems can learn all the extra stuff if you want.A trick to find a function you're looking for on a UNIX system is this:Say that you want to find something that converts ASCII (characters)to integers but you never heard about atoi(), then you can do this:alien:~$ apropos integerThat will show you this:Tcl_GetInt, Tcl_GetDouble, Tcl_GetBoolean (3) - convert from string to integer,double, or booleanTcl_NewIntObj, Tcl_NewLongObj, Tcl_SetIntObj, Tcl_SetLongObj, Tcl_GetIntFromObj,Tcl_GetLongFromObj (3) - manipulate Tcl objects as integersabs (3) - computes the absolute value of an integer.atoi (3) - convert a string to an integer.atol (3) - convert a string to a long integer.

    div (3) - computes the quotient and remainder of integer divisionlabs (3) - computes the absolute value of a long integer.ldiv (3) - computes the quotient and remainder of long integer division.rint (3) - round to closest integerstrtol (3) - convert a string to a long integer.strtoul (3) - convert a string to an unsigned long integer.tixGetInt (n) - Get the integer value of a string. ' ' 'Math::BigInt (3) - Arbitrary size integer math packageinteger (3) - Perl pragma to compute arithmetic in integer instead of doubleline 1/14 (END)And there we go, the 4th down says:atoi (3) - convert a string to an integer.press "q" to get the prompt back:so now you can do:alien:~$ man 3 atoiThe 3 after man comes from "atoi (3)", and "man" means manual.Now you will get up a manual page that has this in it:---------------------------------------SYNOPSIS#include

    int atoi(const char *nptr);---------------------------------------That is the most important part for you.

    First it tells you what header file to include, and then it tells youthe type and syntax of the function.Here, the function is of type int so it may be used as an integer,

  • 8/8/2019 Learn Ansi c

    26/31

    and the syntax of it is: const char *nptr, wich means a char pointer.(press "q" to get out of the man page and back to the prompt)So this means the following, illustrated in a small code://----------------------------------------------------------#include #include int main ( void )

    {char something[10];strcpy ( something, "123" );printf ( "the pointer holds %i\n", atoi ( something ) );return 0;}//----------------------------------------------------------Not very hard is it ?look up the man pages for funtions that you already know to learnhow the manual pages works and are written.-------------------------------------------------------------------------------Now it's time to move on to the next section:

    Share This Posted in Ansi C Tutorial No Comments July 11th, 20075 - Sockets and forking

    ===============================================================================5 - Sockets and forking.===============================================================================In this section there will be alot of new things, socket coding is the codethat makes an application able to connect to another computer or acceptconnections from other computers, this is how the internet works.A socket is an imaginary socket in the computer that opens a portto send or receav something from the internet or a local network.I will first make the example code and then I will explain it,

    so let's go right to the first example of socket coding://----------------------------------------------------------#include #include #include #include #include #include #include #include #include int main ( int argc, char **argv ){struct sockaddr_in address;struct hostent *hp;int port, sock;char buffer[1024];if ( argc < 3 ) {printf ( "Usage: %s \n", argv[0] );exit ( -1 );}if ( ( sock = socket (AF_INET, SOCK_STREAM, 0 ) ) == -1 ) {fprintf ( stderr, "Error\n" );exit ( -1 );}

    printf ( "Resolving hostname...\n" );if ( ( hp = gethostbyname ( argv[1] ) ) == NULL ) {fprintf ( stderr, "Could not resolve %s.\n", argv[1] );

  • 8/8/2019 Learn Ansi c

    27/31

    exit ( -1 );}port = atoi ( argv[2] );printf ( "Connecting to host.\n" );address.sin_family = AF_INET;address.sin_port = htons ( port );address.sin_addr.s_addr = *( u_long * ) hp->h_addr;

    if ( connect ( sock, ( struct sockaddr * ) &address, sizeof ( struct sockaddr )) == -1) {printf ( "Connction refused from host\n" );exit ( -1 );}printf ( "Sending string to host.\n" );sprintf ( buffer, "Something\r\n" );send ( sock, buffer, strlen ( buffer ), 0 );printf ( "Closing connection to host.\n" );close ( sock );return 0;}

    //----------------------------------------------------------So now, what does all this mean ?First we include the needed header files:#include printf() etc.#include exit(), close()#include atoi()#include gethostbyname()#include strlen()#include socket(), send(), connect()#include socket(), send(), connect()#include htons()#include (various inet functions)Then we make and open the main function and then we make the 2 following

    structs:struct sockaddr_in address;struct hostent *hp;Then we have the "if the argument counter is less then 3" thing..Then we have this:if ( ( sock = socket (AF_INET, SOCK_STREAM, 0 ) ) == -1 )AF_INET is the domain, SOCK_STREAM is the type and 0 is the protocol,AF_INET or PF_INET means a normal IP as the domain.SOCK_STREAM means a two-way connectionbased byte stream.and 0 means no protocol.For more info on this, look in the manual page for socket (man 2 socket).From there to "hp = gethostbyname ( argv[1] )" should be undestandeble.gethostbyname() will resolve a hostname, for more info on this functionlook in the manual page.Next new things:address.sin_family = AF_INET;address.sin_port = htons ( port );address.sin_addr.s_addr = *( u_long * ) hp->h_addr;These are declarations of family port and address, you may ask yourself"where does the names "sin_family" etc. come from ?They are defined in netinet/in.h.The next new thing is:if ( connect ( sock, ( struct sockaddr * ) &address, sizeof ( struct sockaddr )) == -1)First the "( sock," comes from:

    if ( ( sock = socket (AF_INET, SOCK_STREAM, 0 ) ) == -1 ) {And is the socket with which we connect to the other computer.Then we have a cast, ( struct sockaddr * ), then we have the address and then

  • 8/8/2019 Learn Ansi c

    28/31

    bit lenth of the address.This may be confusing, but that's the way connect() wants it to work.Next new thing is:send ( sock, buffer, strlen ( buffer ), 0 );This will send the buffer to the socket.send works like this:int send ( int socket, const void *msg, int len, unsigned int flags );

    This tells us that, send is an int.That it wants a sock (which also is an int), a text message (or a pointer toone), the string lenth of the message to send, and any flags, which hereis 0 because we aint using any flags.And then we close the sock and return successful.-------------------------------------------------------------------------------You seriously need to play around some with this and read the source severaltimes to understand it better, you may and should also read thistutorial more then one time to understand everything, and consult itwhen you code things.-------------------------------------------------------------------------------Now let's make another example of socket coding and learn to fork() at the

    same time.A fork detaches a whole program or a bit of it from the main program so thatit can be in the background, so that you may log out from the shell but theprocess is still running, this is how a daemon / server works.Now let's make an example of a daemon.//----------------------------------------------------------#include #include #include #include #include #include #include

    #include #include int main ( void ){pid_t pid;int sock, send_sock, i;struct sockaddr_in addr, info;setsid ( );umask ( 0 );signal ( SIGCHLD, SIG_IGN );if ( fork ( ) ) return 0;sock = socket ( AF_INET, SOCK_STREAM, 0 );addr.sin_family = AF_INET;addr.sin_addr.s_addr = htonl ( INADDR_ANY );addr.sin_port = htons ( 50 );bind ( sock, ( struct sockaddr *) &addr, sizeof ( addr ) );i = sizeof ( info );listen ( sock, 1 );for (;;) {i = sizeof ( info );send_sock = accept ( sock, ( struct sockaddr * ) &info, &i );pid = fork ( );if ( pid ) {close ( send_sock );continue;

    }else {send ( send_sock, "sh-2.03# ", 9, 0 );

  • 8/8/2019 Learn Ansi c

    29/31

    sleep ( 4 );send (send_sock, "\nNah, just kidding :P\n", 24, 0);sleep ( 3 );close ( send_sock );return 0;}}

    return 0;}//----------------------------------------------------------So now what does this mean ?First we include the header files and create a main function.Then we declare pid as pid_t, so that we have a pointer to the pid(process ID), then we make a struct with pointers addr and info.Then we use setsid(), (man 2 setsid for info on it).And after that we use umask(), this is used to set the file premission,you may "man 2 umask", if you wanna know exectly what it does.The we use signal to ignore the sigchld, man 2 signal for more info on whyit acts the way it acts.

    The we say:if ( fork ( ) ) return 0;This means that if the process if forked it should return successfully.Then we create a socket.And after that declare the ports etc. in the struct.Then we use bind:bind ( sock, ( struct sockaddr *) &addr, sizeof ( addr ) );sock is the socket, and then there is the cast, the address and thebit size of the address.Then we say that i is the bit size of info.i = sizeof ( info );And then we say for it to listen on the sock we used bind to open.listen ( sock, 1 );

    The 1 in listen is the backlog (look in the manyal page for this).Then we make a loop that may go on for ever that says:That i is the bit size of info, again .... I had some problems with thecode when it wasnt there.i = sizeof ( info );And then we say that send_sock is like this:send_sock = accept ( sock, ( struct sockaddr * ) &info, &i );this means that send_sock is the accept, and so it's the incoming socketconnection.Then we make sure that the pid is forked and so put to the background,pid = fork ( );If there is a pid, then close the socket and continue......if ( pid ) {close ( send_sock );continue;}.....else do this (if it works out the way it's made to do:.....send ( send_sock, "sh-2.03# ", 9, 0 );sleep ( 4 );send (send_sock, "\nNah, just kidding :P\n", 24, 0);sleep ( 3 );close ( send_sock );

    .....This means send "sh-2.03# " to the user at the other end, and thenwait for 4 seconds and after that send "Nah, just kidding :P",

  • 8/8/2019 Learn Ansi c

    30/31

    wait for another 3 seconds and then close the socket.As we did:addr.sin_port = htons ( 50 );This daemon will be listening on port 50 ...And since we are using raw socks, this will have to be started as user root.Now I know I'm not explaining this as easy as I did with other codes, butI'm doing that for a reason, to make you think and to get more "aha"

    experiances.So that you learn some by your self, else you're likly to just forgetabout it as soon as you read it .... so play around with the code untilyou understand it, and dont be afraid of the manual pages.See how much of the code you can change etc.-------------------------------------------------------------------------------Here is a little code with the forking part alone://----------------------------------------------------------#include "check_tmp.h"/* taken from Stevens APUE */int become_daemon(void){pid_t pid;

    if ( (pid = fork()) < 0)return(-1);else if (pid != 0)exit(0); /* death to the parental unit */setsid();/* we're going to fork again for annoying SYSVr4 to insure thatwe have no controlling terminal */if ( (pid = fork()) < 0)return(-1);else if (pid != 0)exit(0); /* death to the parental unit */chdir("/");umask(0);

    return(0);}//----------------------------------------------------------This code is taken litterly from another source, and I will not change orexplain it, look at it as a little test, of how well you know C by now ....Figure out exectly what it's doing and why, use the manual pages.(No it wont compile as it is, because there is no main function and the headerfiles are missing.)-------------------------------------------------------------------------------Actually there's not much more to say about forking and raw sockets atthis point ... there is ALOT more to sockets, but nothing you need to knowat this point since this is not a socket coding tutorial.So off to the next section.Share This Posted in Ansi C Tutorial 4 Comments July 11th, 2007

    You are currently browsing the archives for the Ansi C Tutorial category.Index Ansi C Tutorial Bash tutorial Hacking tutorial

    Additional resources

    2007 Computer Science Directory. All Rights Reserved.

  • 8/8/2019 Learn Ansi c

    31/31