2011年5月12日 星期四

PF_UNIX/PF_LOCAL


  #include <sys/socket.h>
       #include <sys/un.h>
       #include <stdlib.h>
       #include <stdio.h>
       #include <string.h>

       #define MY_SOCK_PATH "/tmp/test_path"
       #define LISTEN_BACKLOG 50

       #define handle_error(msg) \
           do { perror(msg); exit(EXIT_FAILURE); } while (0)

       int
       main(int argc, char *argv[])
       {
           int fd, conn_fd;
           struct sockaddr_un my_addr, peer_addr;
           socklen_t peer_addr_size;

           fd = socket(PF_UNIX, SOCK_STREAM, 0);
           if (fd == -1)
               handle_error("socket");

           memset(&my_addr, 0, sizeof(struct sockaddr_un));
           my_addr.sun_family = AF_UNIX;
           // using an abstract path, 不会真正创建相应的文件
           strncpy(&my_addr.sun_path[1], MY_SOCK_PATH,
                   sizeof(my_addr.sun_path) - 1);

           if (bind(fd, (struct sockaddr *) &my_addr,
                   sizeof(struct sockaddr_un)) == -1)
               handle_error("bind");

           if (listen(fd, LISTEN_BACKLOG) == -1)
               handle_error("listen");

           /* Now we can accept incoming connections one
              at a time using accept(2) */
           while(1) {
               char buf[255];
               peer_addr_size = sizeof(struct sockaddr_un);
               conn_fd = accept(fd, (struct sockaddr *) &peer_addr,
                            &peer_addr_size);
               if (conn_fd == -1)
                   handle_error("accept");

               /* Code to deal with incoming connection(s)... */
               recv(conn_fd, buf, 255, 0);
               printf("%s\n", buf);
               close(conn_fd);
               break;
           }
           /* When no longer required, the socket pathname, MY_SOCK_PATH
              should be deleted using unlink(2) or remove(3) */
           remove(MY_SOCK_PATH);
       }

sock_client.c
       #include <sys/socket.h>
       #include <sys/un.h>
       #include <stdlib.h>
       #include <stdio.h>
       #include <string.h>

       #define MY_SOCK_PATH "/tmp/test_path"
       #define LISTEN_BACKLOG 50

       #define handle_error(msg) \
           do { perror(msg); exit(EXIT_FAILURE); } while (0)

       int
       main(int argc, char *argv[])
       {
           int fd;
           struct sockaddr_un serv_addr;

           fd = socket(PF_UNIX, SOCK_STREAM, 0);
           if (fd == -1)
               handle_error("socket");

           memset(&serv_addr, 0, sizeof(struct sockaddr_un));
                               /* Clear structure */
           serv_addr.sun_family = AF_UNIX;
           strncpy(&serv_addr.sun_path[1], MY_SOCK_PATH,
                   sizeof(serv_addr.sun_path) - 1);

           if(-1 == connect(fd, (const struct sockaddr *)&serv_addr, sizeof(serv_addr)))
               handle_error("connect");

           send(fd, "hello", sizeof("hello"), 0);

           close(fd);

       }

2011年4月29日 星期五

pipe

void cgi_run(const char* filename)
{
    char buffer[1024] = { 0 };
    int len;
    int pfd[2];
    int status;
    pid_t pid;


    /* create pipe */
    if (pipe(pfd)<0)
        return -1;


    /* fork to execute external program or scripts */
    pid = fork();
    if (pid<0) {
        return 0;
    } else if (pid==0) { /* child process */
        dup2(pfd[1], STDOUT_FILENO);
        close(pfd[0]);


        /* execute CGI */
        execlp(filename, filename, NULL);
        exit(0);
    } else { /* parent process */
        close(pfd[1]);


        /* print output from CGI */
        while((len=read(pfd[0], buffer, 1023))>0) {
            buffer[len] = '\0';
            printf("%s\n", buffer);
        }


        /* waiting for CGI */
        waitpid((pid_t)pid, &status, 0);
    }
}

2011年4月28日 星期四

TCP_NODELAY

How do I use TCP_NODELAY?

First off, be sure you really want to use it in the first place.  It
  will disable the Nagle algorithm (see ``2.11 How can I force a socket
  to send the data in its buffer?''), which will cause network traffic
  to increase, with smaller than needed packets wasting bandwidth.
  Also, from what I have been able to tell, the speed increase is very
  small, so you should probably do it without TCP_NODELAY first, and
  only turn it on if there is a problem.

  Here is a code example, with a warning about using it from Andrew
  Gierth:

         int flag = 1;
         int result = setsockopt(sock,            /* socket affected */
                                 IPPROTO_TCP,     /* set option at TCP level */
                                 TCP_NODELAY,     /* name of option */
                                 (char *) &flag,  /* the cast is historical
                                                         cruft */
                                 sizeof(int));    /* length of option value */
         if (result < 0)
            ... handle the error ...

  TCP_NODELAY is for a specific purpose; to disable the Nagle buffering
  algorithm. It should only be set for applications that send frequent
  small bursts of information without getting an immediate response,
  where timely delivery of data is required (the canonical example is
  mouse movements).

2011年4月26日 星期二

get IP

#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#include <ifaddrs.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(){
struct ifaddrs *ifaddr, *ifa;
int family, s;
char host[NI_MAXHOST];

if (getifaddrs(&ifaddr) == -1){
perror("getifaddrs");
exit(EXIT_FAILURE);
}

for(ifa = ifaddr; ifa!=NULL; ifa = ifa->ifa_next){
family = ifa->ifa_addr->sa_family;
if(family == AF_INET){
s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
if(s != 0){
printf("getnameinfo() failed: %s\n", gai_strerror(s));
exit(EXIT_FAILURE);
}
printf("Interface=%s\t Address=%s\n", ifa->ifa_name, host);
}
}
return 0;
}

2011年4月15日 星期五

Makefile

$?:代表已被更新的 dependencies 的值。
也就是 dependencies 中,比 targets 還新的值。
$@:代表 targets 的值。
$<:代表第一個 dependencies 的值。
$* :代表 targets 所指定的檔案,但不包含副檔名。

2011年4月13日 星期三

GOOD MACRO

#define install_log(f, a...) \
do { \
    printf("INSTALL LOG %s:%d:%s:\r\n", \
        __FILE__, __LINE__, __func__); \
    printf(f, ##a); \
} while (0)

2011年4月1日 星期五

crt

crt1.o

crt1.o
crti.o
crtbegin.o
crtend.o
crtn.o

這五個檔案分別是 startup, initialization, constructor, destructor, finalization
它們通常會被自動地連結( link )到我們的程式。經由這些檔案,我們程式的 main() 才能被呼叫。
當我們告訴編繹器不要使用標準的連結( LDFLAGS = -nostdlib -L${TARGET_PREFIX}/lib ),那我們必須明確地指定這些檔案到編譯參數中。例如

STARTUP_FILES = ${TARGET_PREFIX}/lib/crt1.o \
${TARGET_PREFIX}/lib/crti.o \
${PREFIX}/lib/gcc-lib/${TARGET}/2.95.3/crtbegin.o
END_FILES = ${PREFIX}/lib/gcc-lib/${TARGET}/2.95.3/crtend. \
${TARGET_PREFIX}/lib/crtn.o
LIBS = -lc
OBJS = daemon.o
LINKED_FILES = ${STARTUP_FILES} ${OBJS} ${LIBS} ${END_FILES}
...
daemon: ${OBJS}
$(CC) -o $(EXEC_NAME) ${LINKED_FILES} $(LDFLAGS)

Linker

http://www.cs.utah.edu/dept/old/texinfo/as/gprof.html
http://linux.about.com/library/cmd/blcmdl1_ld.htm

main.c
#include <stdio.h>
int main()
{
    printf("Hello World\r\n");
}

gcc -c main.c
ld -dynamic-linker /lib/ld-linux-x86-64.so.2  /usr/lib/crt1.o /usr/lib/crti.o -lc main.o /usr/lib/crtn.o

2011年3月31日 星期四

link

http://www.lurklurk.org/linkers/linkers.html

Copiler option

I was just looking into this very thing!

Do this in your Makefile...
--------8<--------
DEADCODESTRIP := -Wl,-static -fvtable-gc -fdata-sections -ffunction-sections -Wl,--gc-sections -Wl,-s

foo : foo.c
    g++ $(DEADCODESTRIP) $< -o $@
--------8<--------

Step by step...

-Wl,-static
Link against static libraries.  Required for dead-code elimination.

-fvtable-gc
C++ virtual method table instrumented with garbage collection information for the linker.

-fdata-sections
Keeps data in separate data sections, so they can be discarded if unused.

-ffunction-sections
Keeps funcitons in separate data sections, so they can be discarded if unused.

-Wl,--gc-sections
Tell the linker to garbage collect and discard unused sections.

-s
Strip the debug information, so as to make the code as small as possible.  (I presume that you'd want to do this in a dead-code removal build.)
-g

Produce debugging information in the operating system's native format (stabs, COFF , XCOFF , or DWARF 2). GDB can work with this debugging information.
On most systems that use stabs format, -g enables use of extra debugging information that only GDB can use; this extra information makes debugging work better in GDB but will probably make other debuggers crash or refuse to read the program. If you want to control for certain whether to generate the extra information, use -gstabs+, -gstabs, -gxcoff+, -gxcoff, or -gvms(see below).GCC allows you to use -g with -O. The shortcuts taken by optimized code may occasionally produce surprising results: some variables you declared may not exist at all; flow of control may briefly move where you did not expect it; some statements may not be executed because they compute constant results or their values were already at hand; some statements may execute in different places because they were moved out of loops. -c
Compile or assemble the source files, but do not link. The linking stage simply is not done. The ultimate output is in the form of an object file for each source file.
By default, the object file name for a source file is made by replacing the suffix .c, .i, .s, etc., with .o.
pr
The requirement to link against the static libraries was surprising to me.  But there you go.

2011年3月4日 星期五

GOOD MACRO

#ifdef INSTALL_DEBUG
#define install_debug(f, a...) \
do { \
    printf("INSTALL  DEBUG %s:%d:%s: ", \
        __FILE__, __LINE__, __func__); \
    printk(f, ##a); \
} while (0)
#else
#define install_debug(f, a...) /**/
#endif

2011年2月23日 星期三

develop kernel modules note

make modules SUBDIRS=fs/udf
cat  /var/log/messages to see what error when ismod occurs error like "Unknown symbol in module"

2011年1月27日 星期四

Linux boot over arm

boot start

traps.c in arch\arm\kernel
early_trap_init(void)
{
    memcpy((void *)vectors, __vectors_start, __vectors_end - __vectors_start);
    memcpy((void *)vectors + 0x200, __stubs_start, __stubs_end - __stubs_start);
    memcpy((void *)vectors + 0x1000 - kuser_sz, __kuser_helper_start, kuser_sz);
}



entry-armv.S in arch\arm\kernel

    .equ    stubs_offset, __vectors_start + 0x200 - __stubs_start

    .globl    __vectors_start
__vectors_start:
 ARM(    swi    SYS_ERROR0    )
 THUMB(    svc    #0        )
 THUMB(    nop            )
    W(b)    vector_und + stubs_offset
    W(ldr)    pc, .LCvswi + stubs_offset
    W(b)    vector_pabt + stubs_offset
    W(b)    vector_dabt + stubs_offset
    W(b)    vector_addrexcptn + stubs_offset
    W(b)    vector_irq + stubs_offset
    W(b)    vector_fiq + stubs_offset

    .globl    __vectors_end
__vectors_end:

Linux boot over arm

entry-armv.S in arch\arm\kernel

2011年1月25日 星期二