Thursday, October 14, 2010

File Descriptor

Each running process has a file descriptor table which contains pointers to all open i/o streams.  When a process starts, three entries are created in the first three cells of the table.  Entry 0 points to standard input, entry 1 points to standard output, and entry 2
points to standard error.  Whenever a file or other i/o stream is opened, a new entry is created in this table, usually in the first available empty slot.

int dup(int filedes);

int dup2(int filedes, int filedes2);

Both return: new file descriptor if OK, 1 on error.



The new file descriptor returned by dup is guaranteed to be the lowest-numbered available file descriptor. With dup2, we specify the value of the new descriptor with the filedes2 argument. If filedes2 is already open, it is first closed. If filedes equals filedes2, then dup2 returns filedes2 without closing it.

The new file descriptor that is returned as the value of the functions shares the same file table entry as the filedes argument.

The memory image exists outside the kernel, the file descriptors live inside the kernel. A single file descriptor points to a file. That file may be referenced by multiple file descriptors.

Fact 1. All close() does is closes a single file descriptor for the current process. That drops the usage count on the actual file, when the usage count on the file drops to zero then it is really closed.

Fact 2. When a process terminates, all it's file descriptors that are still open are closed.

Fact 3. All "dup" and "dup2" do are allocate another file descriptor to point to the same file and increase the usage count on the underlying file.

Fact 4. Fork() duplicates the entire memory image AND the file descriptor table. Both processes now continue executing at the same point, the only difference being the parent got the pid of the child, the child got nothing. Duplicating the file descriptor table is like dup() has been called on each open file descriptor.

Fact 5. Exec() replaces the entire memory image with the new program but the file descriptors do not change EXCEPT for the file descriptors marked as FD_CLOEXEC, which are closed.

Fact 6. Pipe() returns two file descriptors, one is readable, one is writeable. A pipe will remain readable until all writeable file descriptors have been closed. Remember if you create a pipe then call fork there are two descriptors that are writeable.

    int fileno(FILE *stream);

Upon successful completion, the fileno() function shall return the integer file descriptor associated with the stream pointed to by stream. Otherwise, the value -1 shall be returned and errno set to indicate the error.

Sunday, October 10, 2010

Cron Tab


Setting up cron jobs in Unix and Solaris
cron is a unix, solaris utility that allows tasks to be automatically run in the background at regular intervals by the cron daemon. These tasks are often termed as cron jobs in unix , solaris.  Crontab (CRON TABle) is a file which contains the schedule of cron entries to be run and at specified times.
1. Crontab Restrictions
You can execute crontab if your name appears in the file /usr/lib/cron/cron.allow.
If that file does not exist, you can use crontab if your name does not appear in the file /usr/lib/cron/cron.deny.
If only cron.deny exists and is empty, all users can use crontab. If neither file exists, only the root user can use crontab. The allow/deny files consist of one user name per line.
2. Crontab Commands
export EDITOR=vi ;to specify a editor to open crontab file.
crontab -e    Edit your crontab file, or create one if it doesn’t already exist.
crontab -l      Display your crontab file.
crontab -r      Remove your crontab file.
crontab -v      Display the last time you edited your crontab file. (This option is only available on a few systems.)
3. Crontab file
Crontab syntax :
A crontab file has five fields for specifying day , date and time followed by the command to be run at that interval.
*     *     *   *    *        command to be executed
-     -     -   -    -
|     |     |   |    |
|     |     |   |    +----- day of week (0 - 6) (Sunday=0)
|     |     |   +------- month (1 - 12)
|     |     +--------- day of        month (1 - 31)
|     +----------- hour (0 - 23)
+------------- min (0 - 59)
* in the value field above means all legal values as in braces for that column.
The value column can have a * or a list of elements separated by commas. An element is either a number in the ranges shown above or two numbers in the range separated by a hyphen (meaning an inclusive range).
The specification of days can be made in two fields: month day and weekday. If both are specified in an entry, they are cumulative meaning both of the entries will get executed .
4. Crontab Example
A line in crontab file like below removes the tmp files from /home/user/tmp each day at 9:30 PM.
30     21     *     *     *         rm /home/user/tmp/*
5. Crontab Environment
cron invokes the command from the user’s HOME directory with the shell, (/usr/bin/sh).
cron supplies a default environment for every shell, defining:
HOME=user’s-home-directory
LOGNAME=user’s-login-id
PATH=/usr/bin:/usr/sbin:.
SHELL=/usr/bin/sh
Users who desire to have their .profile executed must explicitly do so in the crontab entry or in a script called by the entry.
6. Disable Email
By default cron jobs sends a email to the user account executing the cronjob. If this is not needed put the following command At the end of the cron job line .
>/dev/null 2>&1
7. Generate log file
To collect the cron execution execution log in a file :
30 21 * * * rm /home/user/tmp/* > /home/user/logs/clean_tmp_dir.log

Sunday, August 22, 2010

Difference between exit() and _exit()

There are a few differences between exit() and _exit() that become significant when fork(), and especially vfork(), is used.

The basic difference between exit() and _exit() is that the former performs clean-up related to user-mode constructs in the library, and calls user-supplied cleanup functions, whereas the latter performs only the kernel cleanup for the process.

In the child branch of a fork(), it is normally incorrect to use exit(), because that can lead to stdio buffers being flushed twice, and temporary files being unexpectedly removed. In C++ code the situation is worse, because destructors for static objects may be run incorrectly. (There are some unusual cases, like daemons, where the parent should call _exit() rather than the child; the basic rule, applicable in the overwhelming majority of cases, is that exit() should be called only once for each entry into main.)

In the child branch of a vfork(), the use of exit() is even more dangerous, since it will affect the state of the parent process.

The exec() system call

The exec() system call
The exec() functions replace a current process with another created according to the arguments given.
The syntax of these functions is as follows:



#include  

char *env[];

int execl(const char *path, const char *arg0, ..., (char *)0);
int execv(const char *path, const char *argv[]);

int execlp(const char *path, const char *arg0, ..., (char *)0);
int execvp(const char *path, const char *argv[]);

int execle(const char *path, const char *arg0, ... , (char *)0, const char *env[]);
int execve(const char *path, const char *argv[], const char *env[]);

The program given by the path argument is used as the program to execute in place of what is currently running. In the case of the execl() the new program is passed arguments arg0, arg1, arg2,... up to a null pointer. By convention, the first argument supplied (i.e. arg0) should point to the file name of the file being executed. In the case of the execv() programs the arguments can be given in the form of a pointer to an array of strings, i.e. the argv array. The new program starts with the given arguments appearing in the argv array passed to main. Again, by convention, the first argument listed should point to the file name of the file being executed. The function name suffixed with a p (execlp() and execvp())differ in that they will search the PATH environment variable to find the new program executable file. If the executable is not on the path, and absolute file name, including directories, will need to be passed to the function as a parameter. The global variable environ is available to pass a value for the new program environment. In addition, an additional argument to the exec() functions execle() and execve() is available for passing an array of strings to be used as the new program environment.
Examples to run the ls command using exec are:

const char *argv[] = ("ls", "-lrt", 0);

const char *env[] = {"PATH=/bin:/usr/bin", "TERM=console", 0};

execl("/bin/ls", "ls", "-lrt", 0);
execv("/bin/ls", argv);

execlp("ls", "ls", "-lrt", 0);
execle("/bin/ls", "ls", "-lrt", 0, env);

execvp("ls", argv);
execve("/bin/ls", argv, env);

TCP Clients and Servers

The general order of library calls for a TCP client is as follows:
  socket()
  connect()
  send() and/or recv()
  close()

The general order of library calls for a TCP server is as follows:
  socket()
  bind()
  listen()
  accept()
  send() and/or recv()
  close()

 Socket Address Structures
Internet socket addresses are stored in 16-byte structures of the type sockaddr_in defined as follows:

  struct sockaddr_in{
    short sin_family;
    unsigned short sin_port;
    struct in_addr sin_addr;
    char sin_zero[8];
  };

For Internet applications, the sin_family member is always AF_INET, the sin_port member is a 16-bit port number, and the sin_addr member is a 32-bit IP address. The in_addr structure has the following form

  struct in_addr {
    unsigned long s_addr;
  };

Note that the in_addr struct is exactly 4 bytes long, which is the same size as an IP address. The IP address and port number are always stored in network (big-endian) byte order. For example:

  struct sockaddr_in sin;
  sin.sin_family = AF_INET;
  sin.sin_port = htons(9999)
  sin.sin_addr.s_addr = inet_addr("128.227.224.3");

In the above code example, the structure sin holds the IP address 128.227.224.3, and references the port number 9999. Two utility functions are used to set these values. The function htons returns the integer argument passed into it in network byte order. The function inet_addr converts the string argument from a dotted-quad into a 32-bit integer. Its return value is also in network byte order.
TCP Library Calls

socket:
The socket library call has the following prototype:

  int socket(int family, int type, int protocol);

In short, this function creates "an end point for communication". The return value from this function is a handle to a socket. This number is passed as a parameter to almost all of the other library calls. Since the focus of this document is on TCP/IP based sockets, the family parameter should be set to AF_INET. The type parameter can be either SOCK_STREAM (for TCP), or SOCK_DGRAM (for UDP). The protocol field is intended for specifying a specific protocol in case the network model support different types of stream and datagram models. However, TCP/IP only has one protocol for each, so this field should always be set to 0. Example to create a TCP socket:

  int s;
  s = socket(AF_INET, SOCK_STREAM, 0);

connect:
The connect library call has the following prototype:

  int connect(int socket, struct sockaddr_in * address, int address_length);

This function establishes an Internet connection with the server at socket address address. The value of address_length is always sizeof(sockaddr_in). The connect function blocks until either the connection is successfully established, or an error occurs. If successful, the socket descriptor is now ready for reading and writing.

bind:
Before sending and receiving data using a socket, it must first be associated with a local source port and a network interface address. The mapping of a socket to a TCP/UDP source port and IP address is called a "binding". The bind function call is used to declare the mapping between the socket, the TCP/UDP source port, and the network interface device. The prototype for bind is as follows:

  bind(int socket, struct sockaddr_in *address, int address_length);

The first argument is a socket handle (the number returned from the socket function call). The second argument is a sockaddr_in structure. The sin_port field of the address argument is the local source port number associated with this socket. That is, for every "send" operation with this socket, the source port field in the TCP/UDP header gets set with this value. If specifying an exact source port is not required, setting this value to INADDR_ANY(0) allows the operating system to pick any available port number. The sin_addr field specifies which network interface device to use. Since most hosts only have one network interface and only one IP address, this field should be set with the host's own IP address. However, the socket library provides no immediate way for a host to determine its own IP address! However, specifying the value of INADDR_ANY(0) in this field tells the operating system to pick any available interface and address.

The address of the sockaddr_in structure is passed into the bind call, so that the socket will now be ready to communicate with remote hosts. The third parameter passed to bind is the length of the sockaddr_in structure.

Example:

  struct sockaddr_in sin;
  int s;

  s = socket(AF_INET, SOCK_STREAM, 0);
  sin.sin_family = AF_INET;
  sin.sin_port = htons(9999);
  sin.sin_addr.s_addr = INADDR_ANY;
  bind(s, (struct sockaddr *)&sin, sizeof(sin));

  /* s is now a usable TCP socket. Source port is 9999 */

It is recommended that the return from bind be checked; bind will fail by returning -1 if the port that is being requested for use is already taken. When bind is called on a TCP socket, the socket is now ready for the connect or accept calls.

listen:
The server listens for incoming connection requests from clients. The prototype for listen is as follows:

  listen(int socket, int backlog);

The first argument is a socket handle (the number returned from the socket function call). The second argument specifies the maximum number of connections that can be pending on the specified socket (typically set to a large value, such as 1024).

accept:
This is a blocking operation that does not return until a remote client has established a connection; when it completes, it returns a new socket that corresponds to this just-established connection. The prototype for accept is as follows:

  int accept(int socket, struct sockaddr_in * address, int * addr_len);

The address argument contains the remote client's address. Note that when accept returns, the original socket that was given as argument still exists; it is used in a future invocation of accept.

send and recv:
Once a connection is established, the application processes invoke the following two operations to send and receive data:

  int send(int socket, char * message, int msg_len, int flags);
  int recv(int socket, char *buffer, int buf_len, int flags);

Both operations take a set of flags that control certain details of the operation.

Saturday, August 21, 2010

Packet exchange during a complete TCP connection

TCP protocol operations may be divided into three phases. Connections must be properly established in a multi-step handshake process (connection establishment) before entering the data transfer phase. After data transmission is completed, the connection termination closes established virtual circuits and releases all allocated resources.

A TCP connection is managed by an operating system through a programming interface that represents the local end-point for communications, the Internet socket. During the lifetime of a TCP connection it undergoes a series of state changes:

   1. LISTEN : In case of a server, waiting for a connection request from any remote client.
   2. SYN-SENT : waiting for the remote peer to send back a TCP segment with the SYN and ACK flags set. (usually set by TCP clients)
   3. SYN-RECEIVED : waiting for the remote peer to send back an acknowledgment after having sent back a connection acknowledgment to the remote peer. (usually set by TCP servers)
   4. ESTABLISHED : the port is ready to receive/send data from/to the remote peer.
   5. FIN-WAIT-1
   6. FIN-WAIT-2
   7. CLOSE-WAIT
   8. CLOSING
   9. LAST-ACK
  10. TIME-WAIT : represents waiting for enough time to pass to be sure the remote peer received the acknowledgment of its connection termination request. According to RFC 793 a connection can stay in TIME-WAIT for a maximum of four minutes.
  11. CLOSED

TCP Connection Termination

As the saying goes, “all good things must come to an end”… and so it is with TCP connections. The link between a pair of devices can remain open for a considerable period of time, assuming that a problem doesn't force the connection to be aborted. Eventually, however, one or both of the processes in the connection will run out of data to send and will shut down the TCP session, or will be instructed by the user to do so.
Requirements and Issues In Connection Termination

Terminating a TCP connection requires four segments. This is because TCP supports a half-closed state. A half closed state is when one side of the connection sends a close (a FIN) which means that it will no longer send anything, but it is still listening for anything coming from the other side. The connection is completely terminated when the other side sends its FIN segment. Both of the FIN segments have to be acknowledged hence four segments. Furthermore, when the last of these acknowledgments has been sent, the sender has to keep their connection open for 4 minutes. This is known as the TIME_WAIT state.

The standard specifies that the client should wait double a particular length of time called the maximum segment lifetime (MSL) before finishing the close of the connection. The TCP standard defines MSL as being a value of 120 seconds (2 minutes). In modern networks this is an eternity, so TCP allows implementations to choose a lower value if it is believed that will lead to better operation.

There are two reasons for this four minute wait. The first is so that the final ACK can be resent if lost. The server will resend its FIN if it does not receive an ACK within a specified time (known as the retransmission timeout, RTO) and the client stays open long enough so that it will receive the retransmission if sent. The second reason is so that any duplicate segments that have been sent can time out before the port is used again for a new connection (all segments have a limited lifetime on the Internet, they will be simply discarded when this lifetime has expired).

There are two side effects to having a four minute wait. The first limits the number of transactions a client can process a second and the second is concerned with the amount of memory used by keeping a number of connections open.

There are only a finite number of ports available at any time. Since a port address is 16 bits the number of ports is 216 which is 65535. The number of reserved ports is 1023 (reserved for well known servers), so the number of ports available to a client at any time is 65535 - 1023 = 64512. The four minute wait combined with the finite number of available ports means that the number of transactions able to be processed by a client is limited to 64512 / 240 = 268 per second.

For each open connection, the operating system kernel of the host must maintain information about the connection in memory. In a typical Unix TCP/IP implementation each open connection requires 264 bytes of memory. If a host had to keep 64512 connections open at any time this equates to more than 17000000 bytes of memory!

Normal Connection Termination:
Just as TCP follows an ordered sequence of operations to establish a connection, it includes a specific procedure for terminating a connection. As with connection establishment, each of the devices moves from one state to the next to terminate the connection. This process is more complicated than one might imagine it needs to be. In fact, an examination of the TCP finite state machine shows that there are more distinct states involved in shutting down a connection than in setting one up.

The reason that connection termination is complex is that during normal operation, both of the devices are sending and receiving data simultaneously. Usually, connection termination begins with the process on just one device indicating to TCP that it wants to close the connection. The matching process on the other device may not be aware that its peer wants to end the connection at all. Several steps are required to ensure that the connection is shut down gracefully by both devices, and that no data is lost in the process.

Ultimately, shut down of a TCP connection requires that the application processes on both ends of the connection recognize that “the end is nigh” for the connection and stop sending data. For this reason, connection termination is implemented so that each device terminates its end of the connection separately. The act of closing the connection by one device means that device will no longer send data, but can continue to receive it until the other device has decided to stop sending. This allows all data that is pending to be sent by both sides of the communication to be flushed before the connection is ended.

Client
Server
Start State
Action
Transitions To State
Start State
Action
Transitions To State
ESTABLISHED
Client Close Step #1 Transmit: The application using TCP signals that the connection is no longer needed. The client TCP sends a segment with the FIN bit set to request that the connection be closed.
FIN-WAIT-1
ESTABLISHED
At this stage the server is still in normal operating mode.
—
FIN-WAIT-1
The client, having sent a FIN, is waiting for it to both be acknowledged and for the serve to send its own FIN. In this state the client can still receive data from the server but will no longer accept data from its local application to be sent to the server.
—
ESTABLISHED
Client Close Step #1 Receive and Step #2 Transmit: The server receives the client's FIN. It sends an ACK to acknowledge the FIN. The server must wait for the application using it to be told the other end is closing, so the application here can finish what it is doing.
CLOSE-WAIT
FIN-WAIT-1
Client Close Step #2 Receive: The client receives the ACK for its FIN. It must now wait for the server to close.
FIN-WAIT-2
CLOSE-WAIT
The server waits for the application process on its end to signal that it is ready to close.
—
FIN-WAIT-2
The client is waiting for the server's FIN.
—
CLOSE-WAIT
Server Close Step #1 Transmit: The server's TCP receives notice from the local application that it is done. The server sends its FIN to the client.
LAST-ACK
FIN-WAIT-2
Server Close Step #1 Receive and Step #2 Transmit: The client receives the server's FIN and sends back an ACK.
TIME-WAIT
LAST-ACK
The server is waiting for an ACK for the FIN it sent.
—
TIME-WAIT
The client waits for a period of time equal to double the maximum segment life (MSL) time, to ensure the ACK it sent was received.
—
LAST-ACK
Server Close Step #2 Receive: The server receives the ACK to its FIN and closes the connection.
CLOSED
TIME-WAIT
The timer expires after double the MSL time.
CLOSED
CLOSED
The connection is closed on the server's end.

CLOSED
The connection is closed.

CLOSED
The connection is closed.


Simultaneous Connection Termination:
Just as it is possible for the normal connection establishment process to be changed if two devices decide to actively OPEN a connection to each other, it is also possible for two devices to try to terminate a connection simultaneously. This term “simultaneously” doesn't mean that they both decide to shut down at exactly the same time—variances in network delays mean nothing can be simultaneous on an internetwork anyway. It simply means that, in the example above, the client decides to shut down and sends a FIN, but the server sends its own FIN before the client's FIN shows up at the server.

Client


Server


Start State
Action
Transitions To State
Start State
Action
Transitions To State
ESTABLISHED
Client Close Step #1 Transmit: The application using TCP signals that the connection is no longer needed. The TCP on the client sends the next segment with the FIN bit set, indicating a request to close the connection.
FIN-WAIT-1
ESTABLISHED
Server Close Step #1 Transmit: Before the server can receive the FIN sent by the client, the application on the server also signals a close. The server also sends a FIN.
FIN-WAIT-1
FIN-WAIT-1
Server Close Step #1 Receive and Step #2 Transmit: The client has sent a FIN and is waiting for it to be acknowledged. Instead, it receives the FIN sent by the server. It acknowledges the server's close request with an ACK and continues to wait for its own ACK.
CLOSING
FIN-WAIT-1
Client Close Step #1 Receive and Step #2 Transmit: The server has sent a FIN and is waiting for it to be acknowledged. Instead, it receives the FIN sent by the client. It acknowledges the client's close request with an ACK and continues to wait for its own ACK.
CLOSING
CLOSING
Client Close Step #2 Receive: The client receives the ACK for its FIN.
TIME-WAIT
CLOSING
Server Close Step #2 Receive: The server receives the ACK for its FIN.
TIME-WAIT
TIME-WAIT
The client waits for a period of time equal to double the maximum segment life (MSL) time. This gives enough time to ensure the ACK it sent to the server was received.
—
TIME-WAIT
The server waits for a period of time equal to double the maximum segment life (MSL) time. This gives enough time to ensure the ACK it sent to the client was received.
—
TIME-WAIT
The timer expires after double the MSL time.
CLOSED
TIME-WAIT
The timer expires after double the MSL time.
CLOSED
CLOSED
The connection is closed.
—
CLOSED
The connection is closed.
—

Maximum Segment Size (MSS)

The maximum segment size (MSS) is an option of the TCP protocol that specifies the largest amount of data, specified in bytes, that a computer or communications device can receive in a single, unfragmented piece. It does not count the TCP header or the IP header. For optimum communications, the number of bytes in the data segment and the headers must not add up to more than the number of bytes in the maximum transmission unit (MTU).

The MSS is an important consideration in Internet connections. As data is routed over the Internet, it must pass through multiple gateway routers. Ideally, each TCP segment can pass through every router without being fragmented. If the data segment size is too large for any of the routers through which the data passes, the oversized segments are fragmented. This decreases throughput and increases latency, in some cases dramatically. The likelihood of such fragmentation can be minimized by keeping the MSS as small as reasonably possible. Every host is required to be able to handle an MSS of at least 536 bytes.

For most computer users, the MSS option is set automatically by the operating system on the SYN packet during the TCP handshake. Each direction of data flow can use a different MSS.

There is difficulty with understanding these sizes and their relationship due to the variable size of the IP and TCP headers. To resolve the ambiguity in the TCP Maximum Segment Size option definition the following rule is established:

 THE TCP MAXIMUM SEGMENT SIZE IS THE IP MAXIMUM DATAGRAM SIZE MINUS FORTY.

     The default IP Maximum Datagram Size is 576.
     The default TCP Maximum Segment Size is 536.

On receipt of the MSS option the calculation of the size of segment that can be sent is:

 SndMaxSegSiz = MIN((MTU - sizeof(TCPHDR) - sizeof(IPHDR)), MSS)

This begs the question, though.  What value should be used for the
   "sizeof(TCPHDR)" and for the "sizeof(IPHDR)"?

There are three reasonable positions to take: the conservative, the moderate, and the liberal.

The conservative or pessimistic position assumes the worst -- that both the IP header and the TCP header are maximum size, that is, 60 octets each.

      MSS = MTU - 60 - 60 = MTU - 120

      If MTU is 576 then MSS = 456

The moderate position assumes the that the IP is maximum size (60 octets) and the TCP header is minimum size (20 octets), because there are no TCP header options currently defined that would normally be sent at the same time as data segments.

      MSS = MTU - 60 - 20 = MTU - 80

      If MTU is 576 then MSS = 496

The liberal or optimistic position assumes the best -- that both the IP header and the TCP header are minimum size, that is, 20 octets each.

      MSS = MTU - 20 - 20 = MTU - 40

      If MTU is 576 then MSS = 536

If nothing is said about MSS, the data sender may cram as much as possible into a 576 octet datagram, and if the datagram has minimum headers (which is most likely), the result will be 536 data octets in the TCP segment.  The rule relating MSS to the maximum datagram size ought to be consistent with this.

A practical point is raised in favor of the liberal position too. Since the use of minimum IP and TCP headers is very likely in the very large percentage of cases, it seems wasteful to limit the TCP segment data to so much less than could be transmitted at once, especially since it is less that 512 octets.

      For comparison:  536/576 is 93% data, 496/576 is 86% data, 456/576 is 79% data.

What is the Default MSS ?

Another way of asking this question is "What transmitted value for MSS has exactly the same effect of not transmitting the option at all?".

In terms of the previous section:

The default assumption is that the Maximum Transmission Unit is 576 octets.

 MTU = 576

The Maximum Datagram Data Size (MDDS) is the MTU minus the IP header length.

 MDDS = MTU - IPHdrLen = 576 - 20 = 556

When opening a connection TCP can send an MSS option with the value equal MDDS - TCPHdrLen.

 MSS = MDDS - TCPHdrLen = 556 - 20 = 536

TCP should determine the Maximum Segment Data Size (MSDS) from either the default or the received value of the MSS option.

 Default MSS = 536, then MSDS = 536

TCP should determine if source fragmentation is possible and desirable.

If so TCP may hand to IP segments (including the TCP header) up to MSDS + TCPHdrLen (536 + 20 = 556).

If not TCP may hand to IP segments (including the TCP header) up to the lesser of (MSDS + TCPHdrLen (536 + 20 = 556)) and MDDS (556).

Sunday, May 23, 2010

Operators precedence


Precedence Operator Description Example Overloadable Associativity
1 :: Scope resolution operator Class::age = 2; no left to right
2 () Function call printf(“Hello world\n”); yes left to right
() Member initalization c_tor(int x, int y) : _x(x), _y(y * 10) {} yes
[] Array access array[4] = 2; yes
-> Member access from a pointer ptr->age = 34; yes
. Member access from an object obj.age = 34; no
++ Post-increment for (int i = 0; i < 10; i++) cout << i; yes
-- Post-decrement for (int i = 10; i > 0; i--) cout << i; yes
dynamic_cast Runtime-checked type conversion Y& y = dynamic_cast<Y&>(x); no
static_cast Unchecked type conversion Y& y = static_cast<Y&>(x); no
reinterpret_cast Reinterpreting type conversion int const* p = reinterpret_cast<int const*>(0x1234); no
const_cast Cast away/Add constness int* q = const_cast<int*>(p); no
typeid Get type information std::type_info const& t = typeid(x); no
3 ! Logical negation if (!done) ... yes right to left
not Alternate spelling for !
~ Bitwise complement flags = ~flags; yes
compl Alternate spelling for ~
++ Pre-increment for (i = 0; i < 10; ++i) cout << i; yes
-- Pre-decrement for (i = 10; i > 0; --i) cout << i; yes
- Unary minus int i = -1; yes
+ Unary plus int i = +1; yes
* Dereference int data = *intPtr; yes
& Address of int *intPtr = &data; yes
sizeof Size (of the type) of the operand in bytes size_t s = sizeof(int); no
new Dynamic memory allocation long* pVar = new long; yes
new [] Dynamic memory allocation of array long* array = new long[20]; yes
delete Deallocating the memory delete pVar; yes
delete [] Deallocating the memory of array delete [] array; yes
(type) Cast to a given type int i = (int)floatNum; yes
4 ->* Member pointer selector ptr->*var = 24; yes left to right
.* Member object selector obj.*var = 24; no
5 * Multiplication int i = 2 * 4; yes left to right
/ Division float f = 10.0 / 3.0; yes
% Modulus int rem = 4 % 3; yes
6 + Addition int i = 2 + 3; yes left to right
- Subtraction int i = 5 - 1; yes
7 << Bitwise shift left int flags = 33 << 1; yes left to right
>> Bitwise shift right int flags = 33 >> 1; yes
8 < Comparison less-than if (i < 42) ... yes left to right
<= Comparison less-than-or-equal-to if (i <= 42) ... yes
> Comparison greater-than if (i > 42) ... yes
>= Comparison greater-than-or-equal-to if (i >= 42) ... yes
9 == Comparison equal-to if (i == 42) ... yes left to right
eq Alternate spelling for ==
!= Comparison not-equal-to if (i != 42) ... yes
not_eq Alternate spelling for !=
10 & Bitwise AND flags = flags & 42; yes left to right
bitand Alternate spelling for &
11 ^ Bitwise exclusive OR (XOR) flags = flags ^ 42; yes left to right
xor Alternate spelling for ^
12 | Bitwise inclusive (normal) OR flags = flags | 42; yes left to right
bitor Alternate spelling for |
13 && Logical AND if (conditionA && conditionB) ... yes left to right
and Alternate spelling for &&
14 || Logical OR if (conditionA || conditionB) ... yes left to right
or Alternate spelling for ||
15 ? : Ternary conditional (if-then-else) int i = a > b ? a : b; no right to left
16 = Assignment operator int a = b; yes right to left
+= Increment and assign a += 3; yes
-= Decrement and assign b -= 4; yes
*= Multiply and assign a *= 5; yes
/= Divide and assign a /= 2; yes
%= Modulo and assign a %= 3; yes
&= Bitwise AND and assign flags &= new_flags; yes
and_eq Alternate spelling for &=
^= Bitwise exclusive or (XOR) and assign flags ^= new_flags; yes
xor_eq Alternate spelling for ^=
|= Bitwise normal OR and assign flags |= new_flags; yes
or_eq Alternate spelling for |=
<<= Bitwise shift left and assign flags <<= 2; yes
>>= Bitwise shift right and assign flags >>= 2; yes
17 throw throw exception throw EClass(“Message”); no
18 , Sequential evaluation operator for (i = 0, j = 0; i < 10; i++, j++) ... yes left to right

Saturday, May 22, 2010

Function arguments using pointer and reference

void fun_pointer(int *a);
void fun_reference(int &a);

int main()
{
    int *a;
    int b = 5;
    
    a = &b;
    
    //Pointer->Pointer
    fun_pointer(a);

    //NormalObj->Pointer
    fun_pointer(&b);

    //Pointer->Reference   
    fun_reference(*a);
    
    //NormalObj->Reference
    fun_reference(b);
  
    getch();
}

void fun_pointer(int *a)
{}

void fun_reference(int &a)
{}

// Output
main:pointer  :value  :5
main:pointer  :address:0x22ff40
main:reference:value  :5
main:reference:address:0x22ff40

Pointer->Pointer
fun_pointer:value  :5
fun_pointer:address:0x22ff40

NormalObj->Pointer
fun_pointer:value  :5
fun_pointer:address:0x22ff40

Pointer->Reference
fun_reference:value  :5
fun_reference:address:0x22ff40

NormalObj->Reference
fun_reference:value  :5
fun_reference:address:0x22ff40

Fork bomb

A fork bomb works by creating a large number of processes very quickly in order to saturate the available space in the list of processes kept by the computer's operating system. If the process table becomes saturated, no new programs may start until another process terminates. Even if that happens, it is not likely that a useful program may be started since the instances of the bomb program will each attempt to take any newly-available slot themselves.

In addition to using space in the process table, each child process of a fork bomb uses further processor-time and memory. As a result of this, the system and existing programs slow down and become much more unresponsive and difficult or even impossible to use.
 
The following code provides arguably one of the most elegant examples of a fork bomb. The user executes the fork bomb by pasting the following 11 characters into a UNIX shell such as bash or zsh. 

:(){ :|:& };:

Understanding the above:

:()      # define ':' -- whenever we say ':', do this:
{        # beginning of what to do when we say ':'
    :    # load another copy of the ':' function into memory...
    |    # ...and pipe its output to...
    :    # ...another copy of ':' function, which has to be loaded into memory
         # (therefore, ':|:' simply gets two copies of ':' loaded whenever ':' is called)
    &    # disown the functions -- if the first ':' is killed,
         #     all of the functions that it has started should NOT be auto-killed
}        # end of what to do when we say ':'
;        # Having defined ':', we should now...
:        # ...call ':', initiating a chain-reaction: each ':' will start two more.


To keep it simple,
forkbomb(){ forkbomb|forkbomb & } ; forkbomb

OperationFork->init();

Planning to blog the tech things I come across. Well, here's a start!!