亂貼小站公告欄
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<string.h>

struct flock* file_lock(short type,short whence)
{
        static struct flock ret;
        ret.l_type = type;
        ret.l_start = 0;
        ret.l_whence = whence;
        ret.l_len = 0;
        ret.l_pid = getpid();
        return &ret;
}

int main()
{
        printf("1.exclusive lock(write lock)\n");
        printf("2.share lock(read lock)\n");
        printf("Choose lock type -> ");
        int ia;
        scanf("%d",&ia);
        int fd = open("lock.txt",O_RDWR|O_APPEND);
        //printf("fd = %d\n",fd);
        if(ia==1)
        {
                if(fcntl(fd, F_SETLK, file_lock(F_WRLCK, SEEK_SET))==0)
                        printf("F_WRLCK success.\n");
                else 
                {
                        printf("F_WRLCK fail.\n");
                        return 0;
                }
        }
        else
        {
                if(fcntl(fd, F_SETLK, file_lock(F_RDLCK, SEEK_SET))==0)
                        printf("F_RDLCK success.\n");
                else 
                {
                        printf("F_RDLCK fail.\n");
                        return 0;
                }
        }
        ia= 0;
        do
        {
                printf("If you want to unlock file and end program,\n");
                printf("please input 1 -> \n");
                scanf("%d",&ia);
        }while(ia!=1);
        fcntl(fd, F_SETLK, file_lock(F_UNLCK, SEEK_SET));
        close(fd);
}

 

#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<string.h>

struct flock* file_lock(short type,short whence)
{
        static struct flock ret;
        ret.l_type = type;
        ret.l_start = 0;
        ret.l_whence = whence;
        ret.l_len = 0;
        ret.l_pid = getpid();
        return &ret;
}

int main()
{
        printf("1.exclusive lock(write lock)\n");
        printf("2.share lock(read lock)\n");
        printf("3.not use lock\n");
        printf("Choose lock type -> ");
        int ia;
        scanf("%d",&ia);
        int fd = open("lock.txt",O_RDWR|O_APPEND);
        if(ia==1)
        {
                if(fcntl(fd, F_SETLK, file_lock(F_WRLCK, SEEK_SET))!=0)
                        printf("F_WRLCK fail.\n");
                else 
                        printf("F_WRLCK success.\n");
        }
        else if(ia==2)
        {
                if(fcntl(fd, F_SETLK, file_lock(F_RDLCK, SEEK_SET))!=0)
                        printf("F_RDLCK fail.\n");
                else 
                        printf("F_RDLCK success.\n");
        }
        char ca[10000];
        if(read(fd, ca, 10000)<0)printf("Can't read file.\n");
        else
        {
                printf("Read file:\n");
                puts(ca);
        }
        strcpy(ca,"\n\nab write success.\n");
        if(write(fd, ca, strlen(ca))<0)printf("Can't write file.\n");
        else
        {
                printf("write file success.\n");
        }
        fcntl(fd, F_SETLK, file_lock(F_UNLCK, SEEK_SET));
        close(fd);
}

 

/*
mount /dev/sda1 /mnt
mount -o remount,mand /mnt
*/
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<string.h>

struct flock* file_lock(short type,short whence)
{
        static struct flock ret;
        ret.l_type = type;
        ret.l_start = 0;
        ret.l_whence = whence;
        ret.l_len = 0;
        ret.l_pid = getpid();
        return &ret;
}

int main()
{
        printf("1.exclusive lock(write lock)\n");
        printf("2.share lock(read lock)\n");
        printf("Choose lock type -> ");
        int ia;
        scanf("%d",&ia);
        int fd = open("mandlock.txt",O_RDWR|O_APPEND);
        //printf("fd = %d\n",fd);
        if(ia==1)
        {
                if(fcntl(fd, F_SETLK, file_lock(F_WRLCK, SEEK_SET))==0)
                        printf("F_WRLCK success.\n");
                else 
                {
                        printf("F_WRLCK fail.\n");
                        return 0;
                }
        }
        else
        {
                if(fcntl(fd, F_SETLK, file_lock(F_RDLCK, SEEK_SET))==0)
                        printf("F_RDLCK success.\n");
                else 
                {
                        printf("F_RDLCK fail.\n");
                        return 0;
                }
        }
        ia= 0;
        do
        {
                printf("If you want to unlock file and end program,\n");
                printf("please input 1 -> \n");
                scanf("%d",&ia);
        }while(ia!=1);
        fcntl(fd, F_SETLK, file_lock(F_UNLCK, SEEK_SET));
        close(fd);
}

 

#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<string.h>

struct flock* file_lock(short type,short whence)
{
        static struct flock ret;
        ret.l_type = type;
        ret.l_start = 0;
        ret.l_whence = whence;
        ret.l_len = 0;
        ret.l_pid = getpid();
        return &ret;
}

int main()
{
        printf("1.exclusive lock(write lock)\n");
        printf("2.share lock(read lock)\n");
        printf("3.not use lock\n");
        printf("Choose lock type -> ");
        int ia;
        scanf("%d",&ia);
        int fd = open("mandlock.txt",O_RDWR|O_APPEND);
        if(ia==1)
        {
                if(fcntl(fd, F_SETLK, file_lock(F_WRLCK, SEEK_SET))!=0)
                        printf("F_WRLCK fail.\n");
                else 
                        printf("F_WRLCK success.\n");
        }
        else if(ia==2)
        {
                if(fcntl(fd, F_SETLK, file_lock(F_RDLCK, SEEK_SET))!=0)
                        printf("F_RDLCK fail.\n");
                else 
                        printf("F_RDLCK success.\n");
        }
        char ca[10000];
        if(read(fd, ca, 10000)<0)printf("Can't read file.\n");
        else
        {
                printf("Read file:\n");
                puts(ca);
        }
        strcpy(ca,"\n\nab write success.\n");
        if(write(fd, ca, strlen(ca))<0)printf("Can't write file.\n");
        else
        {
                printf("write file success.\n");
        }
        fcntl(fd, F_SETLK, file_lock(F_UNLCK, SEEK_SET));
        close(fd);
}

和風信使 發表在 痞客邦 PIXNET 留言(0) 人氣()

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<sstream>
using namespace std;

int freeFrameList[] = {4,7,8,5,1,2,11,12,10,13,14,15};
int freeFrameCnt = 12, freeFrameIndex = 0;
string frame[16] = {"ee","","","ww","","","gg","","","ff","","","","","",""};
string processA[] = {"ab","ef","cd","gh","xa","ta","ab","cg"};
string processB[] = {"rx","yy","zz","ww","mr","mk","fn","zx"};

void show_all(bool ba=false)
{
        if(!ba)
        {
                for(int i=0;i<79;i++)
                        cout<<"=";
                cout<<endl;
        }
        printf("\n%s\n","ProcessA");
        for(int i=0;i<8;i++)printf(" %-2d",i);
        puts("");
        for(int i=0;i<8;i++)printf("%3s",processA[i].c_str());
        printf("\n\n%s\n","ProcessB");
        for(int i=0;i<8;i++)printf(" %-2d",i);
        puts("");
        for(int i=0;i<8;i++)printf("%3s",processB[i].c_str());
        printf("\n\n%s\n","freeFrameList");
        for(int i=freeFrameIndex;i<freeFrameCnt;i++)printf("%3d",freeFrameList[i]);
        printf("\n\n%s\n","frame");
        for(int i=0;i<16;i++)printf(" %-2d",i);
        puts("");
        for(int i=0;i<16;i++)printf("%3s",frame[i].c_str());
        puts("");puts("");
}

int main()
{
        string sa;
        show_all(true);
        for(int i=0;i<freeFrameCnt && cout<<"Enter next (ProcessName/page No) -> " && getline(cin,sa);i++)
        {
                sa.erase(0,sa.size()-3);
                istringstream ssin(sa);
                char ca;
                int ia;
                ssin>>ca>>ia;
                switch(ca)
                {
                case 'a':case 'A':
                        frame[freeFrameList[freeFrameIndex++]] = processA[ia];
                        break;
                case 'b':case 'B':
                        frame[freeFrameList[freeFrameIndex++]] = processB[ia];
                        break;
                }
                show_all();
        }
}
/*
ProcessA 0
ProcessB 1
ProcessA 4
ProcessB 5
ProcessB 7
ProcessA 7
ProcessA 2
ProcessB 6
*/

和風信使 發表在 痞客邦 PIXNET 留言(0) 人氣()

/*
    gcc -o a a.c -pthread
    ./a && ./a && ./a && ./a && ./a && ./a && ./a && ./a && ./a && ./a
*/
#include <semaphore.h>
#include <pthread.h>
#include <stdio.h>
int count=0;
void inc(void){
        int i=0;
        for(i=0;i<25000000;i++){
                count++;
        }
        pthread_exit(NULL);
}
void dec(void){
        int i=0;
        for(i=0;i<25000000;i++){
                count--;
        }
        pthread_exit(NULL);
}
int main(void){
        int i=0;
        pthread_t id[4];        
        pthread_create(&id[0],NULL,(void*)dec,NULL);
    pthread_create(&id[1],NULL,(void*)inc,NULL);
    pthread_create(&id[2],NULL,(void*)dec,NULL);
    pthread_create(&id[3],NULL,(void*)inc,NULL);
    for(i=0;i<4;i++)
    {
                pthread_join(id[i],NULL);       
        }
        printf("\noutput is %d\n",count);
}

 

/*
    gcc -o a a.c -pthread
    ./a && ./a && ./a && ./a && ./a && ./a && ./a && ./a && ./a && ./a
*/
#include <semaphore.h>
#include <pthread.h>
#include <stdio.h>
int count=0;
sem_t sem;

void inc(void){
        int i=0;
        for(i=0;i<25000000;i++){
        sem_wait(&sem);
                count++;
        sem_post(&sem);
        }
        pthread_exit(NULL);
}
void dec(void){
        int i=0;
        for(i=0;i<25000000;i++){
        sem_wait(&sem);
                count--;
        sem_post(&sem);
        }
        pthread_exit(NULL);
}
int main(void){
    sem_init(&sem,0,1);
        int i=0;
        pthread_t id[4];        
        pthread_create(&id[0],NULL,(void*)dec,NULL);
    pthread_create(&id[1],NULL,(void*)inc,NULL);
    pthread_create(&id[2],NULL,(void*)dec,NULL);
    pthread_create(&id[3],NULL,(void*)inc,NULL);
    for(i=0;i<4;i++)
    {
                pthread_join(id[i],NULL);       
        }
        printf("\noutput is %d\n",count);
    sem_destroy(&sem);
    return 0;
}

 

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include </usr/include/semaphore.h>

#define BUFF_SIZE   5           /* total number of slots */
#define NP          3           /* total number of producers */
#define NC          3           /* total number of consumers */
#define NITERS      4           /* number of items produced/consumed */

typedef struct {
    int buf[BUFF_SIZE];   /* shared var */
    int in;               /* buf[in%BUFF_SIZE] is the first empty slot */
    int out;              /* buf[out%BUFF_SIZE] is the first full slot */
    sem_t full;           /* keep track of the number of full spots */
    sem_t empty;          /* keep track of the number of empty spots */
    sem_t mutex;          /* enforce mutual exclusion to shared data */
} sbuf_t;

sbuf_t shared;

void *Producer(void *arg)
{
    int i, item, index;

    index = (int)arg;

    for (i=0; i < NITERS; i++) {

        /* Produce item */
        item = i;       

        /* Prepare to write item to buf */

        /* If there are no empty slots, wait */
        sem_wait(&shared.empty);
        /* If another thread uses the buffer, wait */
        sem_wait(&shared.mutex);
        shared.buf[shared.in] = item;
        shared.in = (shared.in+1)%BUFF_SIZE;
        printf("[P%d] Producing %d ...\n", index, item); fflush(stdout);
        /* Release the buffer */
        sem_post(&shared.mutex);
        /* Increment the number of full slots */
        sem_post(&shared.full);

        /* Interleave  producer and consumer execution */
        if (i % 2 == 1) sleep(1);
    }
    return NULL;
}

void *Consumer(void *arg)
{
    /* Fill in the code here */
    int i, item, index;

    index = (int)arg;

    for (i=0; i < NITERS; i++) {
        /* Prepare to read item from buf */

        /* If there are no full spots, wait */
        sem_wait(&shared.full);
        /* If another thread uses the buffer, wait */
        sem_wait(&shared.mutex);
        
        /* Consume item */
        item = shared.buf[shared.out];
        shared.out = (shared.out+1)%BUFF_SIZE;
        printf(" ------> [P%d] Consuming %d ...\n", index, item); fflush(stdout);
        /* Release the buffer */
        sem_post(&shared.mutex);
        /* Increment the number of full slots */
        sem_post(&shared.empty);

        /* Interleave  producer and consumer execution */
        if (i % 2 == 1) sleep(1);
    }
    return NULL;
}

int main()
{
    pthread_t idP, idC;
    int index;

    sem_init(&shared.full, 0, 0);
    sem_init(&shared.empty, 0, BUFF_SIZE);

    /* Insert code here to initialize mutex*/
    sem_init(&shared.mutex, 0, 1);

    for (index = 0; index < NP; index++)
    {  
       /* Create a new producer */
       pthread_create(&idP, NULL, Producer, (void*)index);
    }

    /* Insert code here to create NC consumers */
    for (index = 0; index < NC; index++)
    {  
       /* Create a new producer */
       pthread_create(&idC, NULL, Consumer, (void*)index);
    }

    pthread_exit(NULL);
}

和風信使 發表在 痞客邦 PIXNET 留言(0) 人氣()

/*
Step1: Using the fork() function to create a new process.

Step2: Using command line to kill the process.
        kill -kill 1899

Step3: Repeat step1 and use system calls to kill process.
        
*/
#include<stdio.h>
#include<unistd.h>

int main()
{
    pid_t newpid = fork();
    if(newpid==0)
    {
        for(;;)
            pause();
    }
    printf("pid = %d\n",newpid);
    wait(NULL);
    printf("Child process is finished.\n");
}

 

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

int main()
{
    pid_t newpid;
    printf("Input the pid of the process you want to kill -> ");
    scanf("%d",&newpid);
    kill(newpid,SIGKILL);
}

 

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

struct sigaction newact;

/* here is the signal handler */ 
void catch_alarm_2(int sig_num)   /* the argument is signal number  */
{   
    /* re-set the signal handler again to catch_int, for next time */
    sigaction(SIGINT, &newact, NULL);
}
void catch_int_1(int sig_num)   /* the argument is signal number  */
{   
    /* re-set the signal handler again to catch_int, for next time */
    signal(SIGINT, catch_int_1);
    printf("How are you?\n",sig_num);
}
void catch_int_2(int sig_num)   /* the argument is signal number  */
{   
    /* re-set the signal handler again to catch_int, for next time */
    signal(SIGINT, catch_int_2);
    printf("I am fine!\n",sig_num);
}
void catch_alarm_1(int sig_num)   /* the argument is signal number  */
{   
    /* re-set the signal handler again to catch_int, for next time */
    signal(SIGINT, catch_int_2);
    signal(SIGALRM, catch_alarm_2);
    alarm(3);
}

int main(int argc, char* argv[])
{
    sigaction(SIGINT, NULL, &newact);
    
    /* set the INT (Ctrl-C) signal handler to 'catch_int' */
    signal(SIGINT, catch_int_1);
    signal(SIGALRM, catch_alarm_1);
    alarm(3);

    /* now, lets get into an infinite loop of doing nothing. */
    for ( ;; )
        pause();
} 

和風信使 發表在 痞客邦 PIXNET 留言(0) 人氣()

/*
Compile Command:
    gcc -o a a.c -pthread
*/
#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>

void *PrintHello(void *arg)
{
    printf("This is Hello Thread\n");
    printf("Thread ID:%lu\n",pthread_self());
    printf("Argument: %d\n",(int)arg);
    //printf("Argument: %d\n",*(int*)arg);
    pthread_exit(NULL);
}
 
int main()
{
    pthread_t thread;
    int rc,t=100;
    rc = pthread_create( &thread, NULL, PrintHello, (void*)t);
    if(rc)
    {
        printf("ERROR: return code from pthread_create() is %d\n",rc);
        exit(-1);
    }
    rc = pthread_join( thread, NULL);
    if(rc)
    {
        printf("ERROR: return code from pthread_join() is %d\n",rc);
        exit(-1);
    }
    return 0;
}

 

/*
Compile Command:
    gcc -o b b.c -pthread
 
Questions:
#   Observe all of the results you got, and think about what
    problem does it have? (10pts.)
#   Compare to fork() process by doing all the same thing to
    the global variable, can you figure out what’s the
    difference between them? (10pts.)
 
*/
#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
 
int count = 0;
 
void *PrintHello(void *arg)
{
    int ia=250000;
    //printf("%d) Start: count = %d\n",(int)arg, count);
    while(ia--)
    {
        count++;
        //usleep(1);
    }
    //printf("%d) End: count = %d\n",(int)arg, count);
    printf("Thread %d: ID %lu Completed.\n",(int)arg,pthread_self());
    pthread_exit(NULL);
}
 
int main()
{
    pthread_t thread[4];
    int rc,t;
    for(t=0;t<4;t++)
    {
        rc = pthread_create( &thread[t], NULL, PrintHello, (void*)t);
        if(rc)
        {
            printf("ERROR: return code from pthread_create() is %d\n",rc);
            exit(-1);
        }
    }
    for(t=0;t<4;t++)
    {
        rc = pthread_join( thread[t], NULL);
        if(rc)
        {
            printf("ERROR: return code from pthread_join() is %d\n",rc);
            exit(-1);
        }
    }
    printf("Value = %d\n",count);
    return 0;
}

 

/*
Compile Command:
    gcc -o c c.c -pthread
 
*/
#include<pthread.h>
#include<unistd.h>
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<stdlib.h>
#include "msg_que.h"
 
long int ProgramID = 1; // 1 or 2
int closeMsgQue = 0;
 
void *MsgSend(void *arg)
{
    key_t key=0x1234;
        int msqid = msgget(key,IPC_CREAT | 0666);
        oslab_msg_st msg_buffer;
        while( printf("Enter some text: "),fgets(msg_buffer.msg_text,256,stdin))
        {
                msg_buffer.oslab_msg_type = ProgramID;
                msgsnd(msqid,(void*)&msg_buffer,sizeof(msg_buffer)-sizeof(long int),0);
                if(strcmp(msg_buffer.msg_text,"exit\n")==0)
                {
            closeMsgQue = 1;
                        break;
        }
        }
    pthread_exit(NULL);
}
void *MsgGet(void *arg)
{
    key_t key=0x1234;
        int msqid = msgget(key,IPC_CREAT | 0666);
        oslab_msg_st msg_buffer;
        struct msqid_ds msq_id;
        msgctl(msqid,IPC_STAT,&msq_id);
        while( msgrcv(msqid,(void*)&msg_buffer,sizeof(msg_buffer)-sizeof(long int),3-ProgramID,0) )
        {
                printf("Received: %s\n",msg_buffer.msg_text);
                if(strcmp(msg_buffer.msg_text,"exit\n")==0)
                {
                        if(closeMsgQue)msgctl(msqid,IPC_RMID,&msq_id);
                        break;
                }
        }
    pthread_exit(NULL);
}
 
int main()
{
    pthread_t thread[2];
    int rc,t;
    rc = pthread_create( &thread[0], NULL, MsgSend, (void*)t);
    if(rc)
    {
        printf("ERROR: return code from pthread_create() is %d\n",rc);
        exit(-1);
    }
    rc = pthread_create( &thread[1], NULL, MsgGet, (void*)t);
    if(rc)
    {
        printf("ERROR: return code from pthread_create() is %d\n",rc);
        exit(-1);
    }
    rc = pthread_join( thread[0], NULL);
    if(rc)
    {
        printf("ERROR: return code from pthread_join() is %d\n",rc);
        exit(-1);
    }
    rc = pthread_join( thread[1], NULL);
    if(rc)
    {
        printf("ERROR: return code from pthread_join() is %d\n",rc);
        exit(-1);
    }
    return 0;
}

和風信使 發表在 痞客邦 PIXNET 留言(1) 人氣()

不知道從何時開始

我想要用 webATM 時,

總是會困擾於 ActiveX 不會提示的問題

現在 我終於找的一個解決辦法了

雖然說我覺得這個解決辦法不是治本之道

我找到的這個方法是 重設IE9

http://support.microsoft.com/kb/923737/zh-tw#fixit4me

目前我試了,的確是有用:)


和風信使 發表在 痞客邦 PIXNET 留言(1) 人氣()

20111029-1.jpg  


和風信使 發表在 痞客邦 PIXNET 留言(0) 人氣()

這個章節一開始,傑瑞米.邊沁所提到的功利主義,我乍看之下,覺得他講的就是多數決,投票。但是在看了書裡所提到的案例之後,對其泯滅人性的情形,深感恐懼。捫心自問,如我是我自己在船難中,毫無疑問的我都不想當吃人或是被吃的角色,但是在緊急的狀態下,就應該有緊急的應變措施,那個年輕人被內定真的是很不應該的一件事情,如果真的是用抽籤的,我倒覺得沒什麼太大的不公平處。但是其他人生還之後,都應該接受司法的譴責,以安慰那名年輕人的在天之靈。

我一開始,會把功利主義,跟多數決畫上等號,所以我一開始倒是覺得這感覺上沒什麼大問題,後來,在看了書裡所提到的案例,我才發現我早已走進了一大誤區,也終於體會到了功利主義的恐怖之處。原來功利主義,和多數決的差異,在於功利主義是只有「少數人」擁有決定的權利,而並非所有人都有決定的權利,雖然其核心理念「最大多數人的最大幸福」還是一樣的。但是只要功利主義,被誤用在一些不適當的地方,如書裡所提到的爆炸的油箱、牛津女生夜渡資(這兩個最令我印象深刻),就會造成社會大眾的不愉快。

在書裡提到的爆炸的油箱,他居然把人命和車子的成本做比較,雖然說這個觀點並非毫無理論可循,但是,居然如此的看輕人命的價值,才會導致群起公憤。看完這個例子,我不由自主的想,如果說他為了把車子的安全問題弄得更好,相信車子的賣價也會提高,這樣買的人就會變少;但是以另一個方面想,雖然說因為成本考量,所以沒有辦法把車子弄得更安全,可是買的人會比較多,賠償金也會需要比較多。老實說遇到這種兩難的情境,真的是不好決定,如果當初那個公司為了做出這個決定,而真的有弄出這麼一張評估表的話,這個東西真的該被判定為商業機密,因為這個真的是泯滅人性,人都不會希望自己變成最衰的那個人。

牛津女生夜渡資,一夜50便士,其實這真的還蠻好笑的,在這件事情上,錯用了功利主義,完全沒有考慮到人,以至於整件事情,淪為笑柄。

在這一章的後面,提到了約漢.彌爾,他為了挽救功利主義,提出了一些改進之處。其中,我覺得「只要不妨礙到他人,人人皆有為所欲為的自由」這句話真的非常有道理,我也非常認同。功利主義真的不該被誤用,人類沒有了人性,還能被稱作人類嗎?


和風信使 發表在 痞客邦 PIXNET 留言(0) 人氣()

資料取自:http://blog.longwin.com.tw/2011/10/paper-gnu-grep-fast-2011/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+tsungblog+%28Tsung%27s+Blog%29

Linux shell 常常會用到 grep, 為何 grep 可以那麼快的找到我們要的資料?

這篇文章有清楚的說明: 為什麼 GNU grep 這麼快 (下述摘錄自此文), 詳細討論原文: why GNU grep is fast

為什麼 GNU grep 這麼快? GNU grep 有使用下述技巧:

  • 技巧1: GNU grep之所以快是因為它並不會去“檢查”輸入中的每一個位元組
  • 技巧2: GNU grep之所以快是因為它只對每個它要檢查的位元組執行非常少的操作
  • GNU grep使用了非常著名的 Boyer-Moore 演算法,它會從目標字元串的最後一個字元開始查找,並且配合一個查找表,它可以在發現一個不匹配字元之後,計算出應該跳過後續輸入中的多少個字元並繼續查找

 


和風信使 發表在 痞客邦 PIXNET 留言(0) 人氣()

<%@page contentType="text/html; charset=utf8" import="java.util.*" %>
<%@ include file="20111019_DBSetup.jsp" %>
<% 
request.setCharacterEncoding("utf8");
if( request.getParameter("username") != null )
{
        // 檢查
        String query ;
        query = "select * from `account` where `username` = '"+request.getParameter("username")+"' and `password` = '"+request.getParameter("password")+"'";
        ResultSet res = stmt.executeQuery(query);
        if(res.next())
        {
                out.println("<h1 style=\"color:red\">帳號 "+request.getParameter("username")+" 登入成功</h1>");
                session.setAttribute("Login","OK");    // 設定 session
                response.sendRedirect("20111019_memberQuery.jsp");  // 轉換網頁。
        }
        else
        {
                out.println("<h1 style=\"color:red\">帳號或密碼錯誤</h1>");
        }
        res.close();
}
else
{
        String Login = (String)session.getAttribute("Login");
        if(Login != null && Login.equals("OK"))
        {
                out.println("<h1 style=\"color:red\">welcome.</h1>");
                response.setHeader("Refresh","1;url=20111019_memberQuery.jsp");  // 延遲五秒後轉向
        }
        else
        {%>
<html><head><title>memberAdd</title></head><body>
<form action="" method="post">
        帳號:<input type="text" name="username" value="taichunmin"/><br />
        密碼:<input type="password" name="password" value="1234" />
        <input type="submit" value="登入" />
</form>

</body></html>
        <%}
}
%>

 

<%@page contentType="text/html; charset=utf8" import="java.util.*" %>
<%@ include file="2011.10.19_DBSetup.jsp" %>
<html>
        <head><title>query</title></head>
        <body>
        <div><a href="20111019_memberAdd.jsp">新增使用者</a> <a href="20111019_memberLogin.jsp">使用者登入</a> <a href="20111019_memberLogout.jsp">使用者登出</a></div>
        <table width="100%" cellspacing="0" border="1">
        <%
                String query = "select * from `account` order by `username`";
                ResultSet res = stmt.executeQuery(query);
                while(res.next())
                {
                        out.println("<tr>");
                        String username = res.getString("username");
                        out.println("<td>"+username+"</td>");
                        out.println("<td>"+res.getString("password")+"</td>");
                        out.println("<td><a href=\"20111019_memberUpdate.jsp?username=" + username + "\">修改</a></td>");
                        out.println("<td><a href=\"20111019_memberDelete.jsp?username=" + username + "\">刪除</a></td>");
                        out.println("</tr>");
                }
                res.close();
        %>
        </table>
        </body>
</html>

 

<%@page contentType="text/html; charset=utf8" import="java.util.*" %>
<%@ include file="20111019_DBSetup.jsp" %>
<% 
        session.setAttribute("Login",null);    // 設定 session
        response.sendRedirect("20111019_memberQuery.jsp");  // 轉換網頁。
%>

 

<%@page contentType="text/html; charset=utf8" import="java.util.*" %>
<%@ include file="20111019_DBSetup.jsp" %>
<% 
request.setCharacterEncoding("utf8");
if( request.getParameter("username") != null )
{
        if( request.getParameter("password") != null )
        {
                String query ;
                query = "select * from `account` where `username` = '"+request.getParameter("username")+"' and `password` = '"+request.getParameter("password")+"'";
                ResultSet res = stmt.executeQuery(query);
                if(res.next())
                {
                        if(request.getParameter("password_n1")!=null && request.getParameter("password_n2")!=null && request.getParameter("password_n1").equals(request.getParameter("password_n2")))
                        {
                                query = "update `account` set `password` = ? where `username`=?";
                                pstmt = conn.prepareStatement(query);
                                pstmt.setString(1, request.getParameter("password_n1"));
                                pstmt.setString(2, request.getParameter("username"));
                                pstmt.executeUpdate();
                                response.sendRedirect("20111019_memberQuery.jsp");  // 立即轉換網頁
                        }
                }
                else
                {
                        out.println("<h1 style=\"color:red\">帳號或密碼錯誤</h1>");
                }
                res.close();
        }
}
else
{
        out.println("<h1 style=\"color:red\">沒有 username = "+request.getParameter("username")+"</h1>");
        response.sendRedirect("20111019_memberQuery.jsp");  // 轉換網頁。
}
%>
<html><head><title>memberAdd</title></head><body>
<form action="" method="post">
        <input type="hidden" name="username" value="<%= request.getParameter("username") %>" />
        舊密碼:<input type="password" name="password" value="1234" />
        新密碼:<input type="password" name="password_n1" value="12345" />
        確認密碼:<input type="password" name="password_n2" value="12345" />
        <input type="submit" value="登入" />
</form>

</body></html>

 

<%@page contentType="text/html; charset=utf8" import="java.util.*" %>
<%@ include file="20111019_DBSetup.jsp" %>
<% 
request.setCharacterEncoding("utf8");
if( request.getParameter("username") != null )
{
        // 檢查
        String query ;
        query = "select * from `account` where `username` = '"+request.getParameter("username")+"'";
        ResultSet res = stmt.executeQuery(query);
        if(!(res.next()==true))
        {
                query = "insert into `account` (`username`,`password`) values (?,?)";
                pstmt = conn.prepareStatement(query);
                pstmt.setString(1, request.getParameter("username"));
                pstmt.setString(2, request.getParameter("password"));
                pstmt.executeUpdate();
                response.sendRedirect("20111019_memberQuery.jsp");  // 立即轉換網頁
        }
        else
        {
                out.println("<h1 style=\"color:red\">帳號 "+request.getParameter("username")+" 重複</h1>");
                response.setHeader("Refresh","5;url=20111019_memberQuery.jsp");  // 延遲五秒後轉向
        }
        res.close();
}
%>
<html><head><title>memberAdd</title></head><body>
<form action="" method="post">
        帳號:<input type="text" name="username" value="taichunmin"/><br />
        密碼:<input type="password" name="password" value="1234" />
        <input type="submit" value="Add" />
</form>

</body></html>

 

<%@page contentType="text/html; charset=utf8" import="java.util.*" %>
<%@ include file="20111019_DBSetup.jsp" %>
<% 
request.setCharacterEncoding("utf8");
if( request.getParameter("username") != null )
{
        String query;
        query = "delete from `account` where `username`=?";
        pstmt = conn.prepareStatement(query);
        pstmt.setString(1, request.getParameter("username"));
        pstmt.executeUpdate();
        response.sendRedirect("20111019_memberQuery.jsp");
}
%>
<html><head><title>memberAdd</title></head><body>
<form action="" method="post">
        帳號:<input type="text" name="username" value="taichunmin"/><br />
        <input type="submit" value="delete" />
</form>

</body></html>

 

<%@ page import="java.sql.*" %>
<%!
        Connection conn;
        PreparedStatement pstmt = null;
        Statement stmt = null;
%>
<%
        try{
                Class.forName("org.gjt.mm.mysql.Driver");
                String user="root",password="mis",dbName="db20111019";  // 在課堂上的設定
                //String user="jsp",password="mis",dbName="test";  // 在宿舍的設定
                String url="jdbc:mysql://localhost:3306/"+dbName+"?characterEncoding=utf8&useUnicode=true";
                conn = DriverManager.getConnection(url,user,password);
                stmt = conn.createStatement();
        }catch(SQLException sqle)
        {
                out.println("Sql Exception: "+sqle);
        }
%>

和風信使 發表在 痞客邦 PIXNET 留言(0) 人氣()

找更多相關文章與討論