201_Qt5.3.2Code

1、

2、

02_01_getpid : 

#include <iostream>

using namespace std;

int main()
{
    pid_t id = getpid();
    cout << "Hello World! pid : " << id << endl;
    return 0;
}

 

02_04_01_forkd :

#include <iostream>
#include <stdio.h>

using namespace std;

int main()
{
    pid_t pidChild = fork();
    if (! pidChild)
    {
        cout << "In child process (cout)." << endl;
        printf("In child process (printf).");
        return 0; // ZC: 使用这一句,和 下面的 作比较,还是有区别的...
        //_exit(0); // ZC: 使用这一句时,貌似上面的printf信息打印不出来...难道是信息还没来的及显示 进程就关闭了,的原因?
    }

    cout << "In parent process . Child process id is : " << pidChild << endl;
    return 0;
}

 

02_05_01_TestSystem :

#include <iostream>
#include <stdio.h>

using namespace std;

//#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>

int main()
{
    int iRst = system("exec ls -l");
    if (! WIFEXITED(iRst))
        printf("abnormal exit.\n");
    cout << "Hello World!" << endl;
    return 0;
    //_exit(0s);
}

 

3、

03_01_rwexa :

#include <iostream>
using namespace std;

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

// ZC:  程序功能:打开一个文件,往文件中写入数据

int main()
{
    perror("ZZZ");

    int fd = open("rwexam", O_TRUNC | O_CREAT | O_WRONLY, 0644); // ZC: 注意,这里是 O_CREAT而非O_CREATE!!
    if (fd < 0)
    {
        perror("open");
        _exit(1);
    }

    if (write(fd, "Hello world !\n", 14) != 14)
    {
        perror("write");
        _exit(1);
    }

    close(fd);
    cout << "Hello World!" << endl;
    return 0;
}

 

03_02_catexa :

#include <iostream>
using namespace std;

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>

// ZC: 程序功能:模拟 命令cat的功能

int main(int _argc, const char** _argv)
{
    int fd = open(_argv[1], O_RDONLY, 0666);
    if (fd < 0)
    {
        perror("open");
        _exit(1);
    }

    int iReadLen = 0;
    char buf[1024] = {0};
    while ( (iReadLen = read(fd, buf, sizeof(buf))) > 0 )
    {
        int iWriteLen = write(1, buf, iReadLen);
        if (iWriteLen != iReadLen)
        {
            perror("write");
            _exit(1);
        }
    }

    if (iReadLen < 0)
    {
        perror("read");
        _exit(1);
    }

    cout << "Hello World!" << endl;
    return 0;
}

 

03_03_statexa :

#include <iostream>
using namespace std;

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <sys/time.h>

#define TIME_STRING_BUF 50

// ZC: 获取文件的属性

char* TimeString(time_t _t, char *_buf)
{
    struct tm *tmLocal = localtime(&_t);
    strftime(_buf, TIME_STRING_BUF, "%c", tmLocal); // ZC: 这里使用"%c",得到了时间字符串
    return  _buf;
}

int StatFile(const char* _pcFileName)
{
    struct stat bufStat = {0};
    char bufTime[TIME_STRING_BUF] = {0};
    if (lstat(_pcFileName, &bufStat))
    {
        fprintf(stderr, "Could not lstat %s : %s\n", _pcFileName, strerror(errno));
        return 1;
    }

    printf("[1] File name : %s\n", _pcFileName);
    printf("[2] On device : major %d / minor %d    inode number : %ld\n",
           major(bufStat.st_dev), minor(bufStat.st_dev), bufStat.st_ino);
    printf("[3] Size : %-10ld    type : %07o    permission : %05o\n",
           bufStat.st_size, bufStat.st_mode & S_IFMT, bufStat.st_mode & (~S_IFMT));
    printf("[4] Owner's id : %d    group's id : %d    number of links : %d\n",
           bufStat.st_uid, bufStat.st_gid, bufStat.st_nlink);
    printf("[5] Change time  : %s\n",   TimeString(bufStat.st_ctime, bufTime));
    printf("[6] Modified time  : %s\n", TimeString(bufStat.st_mtime, bufTime));
    printf("[7] Access time  : %s\n",   TimeString(bufStat.st_atime, bufTime));

    return 0;
}

int main(int _argc, const char ** _argv)
{
    int rc = 0;
    for (int i=1; i<_argc; i++)
    {
        rc |= StatFile(_argv[i]);
        if ((_argc - i) > 1)
        {
            printf("\n");
        }
    }

    cout << "Hello World!" << endl;
    return rc;
}

 

03_04_chkflg :

//#include <iostream>
//using namespace std;

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <sys/time.h>
#include <fcntl.h>
#include <sys/ioctl.h>


// ZC: 这里尝试了几次...
//  先用尝试使用"/usr/src/kernels/2.6.32-358.el6.x86_64/include/linux/ext3_fs.h" --> 缺少某些宏定义 --> 不知到该怎么弄 --> 失败,放弃
//  后尝试使用 IDE提示的 linux/ext2_fs.h --> 缺少某些宏定义 --> 不知到该怎么弄 --> 失败,放弃
//  最后使用了 "/usr/include/linux/fs.h" ...
#include <linux/fs.h>
//#include <linux/ext2_fs.h>
//#include </usr/include/linux/byteorder/little_endian.h>
//#include <linux/ext3_fs.h>

// ZC: 程序功能:查看显示文件的 Inode flags

int main(int _argc, const char** _argv)
{
    const char **ppcFilename = _argv+1;
    while (*ppcFilename)
    {
        int fd = open(*ppcFilename, O_RDONLY);
        if (fd < 0)
        {
            fprintf(stderr, "Can not open %s : %s\n", *ppcFilename, strerror(errno));
            return 1;
        }

        int iFlags = 0;
        //if (ioctl(fd, EXT3_IOC_GETFLAGS, &iFlags))
        //if (ioctl(fd, EXT2_IOC_GETFLAGS, &iFlags))
        if (ioctl(fd, FS_IOC_GETFLAGS, &iFlags))
        {
            fprintf(stderr, "ioctl failed on %s : %s\n", *ppcFilename, strerror(errno));
            return 1;
        }

        printf("%s : ", *ppcFilename++); // ZC: 先用*ppcFilename传入函数,然后ppcFilename再++

        //if (iFlags & EXT3_APPEND_FL)
        //if (iFlags & EXT2_APPEND_FL)
        if (iFlags & FS_APPEND_FL)
            printf("append");
        //if (iFlags & EXT3_IMMUTABLE_FL)
        //if (iFlags & EXT2_IMMUTABLE_FL)
        if (iFlags & FS_IMMUTABLE_FL)
            printf("immutable");
        //if (iFlags & EXT3_SYNC_FL)
        //if (iFlags & EXT2_SYNC_FL)
        if (iFlags & FS_SYNC_FL)
            printf("sync");
        //if (iFlags & EXT3_NODUMP_FL)
        //if (iFlags & EXT2_NODUMP_FL)
        if (iFlags & FS_NODUMP_FL)
            printf("nodump");
        printf("\t flags : %08X", iFlags); // ZC: FS_EXTENT_FL(0x00080000) 是指该文件是使用ext?文件系统来存储的?
        printf("\n");
        close(fd);
    }

    return 0;
}

 

03_05_mknodexa :

//#include <iostream>
//using namespace std;

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <sys/time.h>
#include <fcntl.h>
#include <sys/ioctl.h>
//#include <mkdev.h>


// ZC: 程序功能:模拟 命令mknod的功能 (具体 mknod的用法等概念还是比较模糊 ...)
// ZC: 由于 命令"mknod"不太会用,所以 本程序也就没有测试,防止将OS搞坏...

void Usage()
{
    fprintf(stderr, "Usage : mknodexa <path> [b|c|u|p] <major> <minor>\n");
    _exit(1);
}

int main(int _argc, const char ** _argv)
{
    if (_argc < 3)
    {
        Usage();
        _exit(1);
    }

    int iMode = 0666;
    printf("mode : %d(0x%08X)", iMode, iMode);

    int iArgs = 0;
    const char* pcPath = _argv[1];
    if (! strcmp(_argv[2], "b"))
    {
        iMode |= S_IFBLK;
        iArgs = 5;
    }
  //else if ( !strcmp(_argv[2], "c") ||  strcmp(_argv[2], "u") ) // ZC: 貌似查看了 mknod的解释,感觉后半段少一个"!" !!
    else if ( !strcmp(_argv[2], "c") || !strcmp(_argv[2], "u") ) // ZC: 个人感觉应该是这样
    {
        iMode |= S_IFCHR;
        iArgs = 5;
    }
    else if (! strcmp(_argv[2], "p"))
    {
        iMode |= S_IFIFO;
        iArgs = 3;
    }
    else
    {
        fprintf(stderr, "Unknown node type : %s\n", _argv[2]);
        return 1;
    }

    char *pcEnd = NULL;
    int iMajor = 0, iMinor = 0;
    if (iArgs == 5)
    {
        iMajor = strtol(_argv[3], &pcEnd, 0);
        if (*pcEnd)
        {
            fprintf(stderr, "Bad major number : %s\n", _argv[3]);
            return 1;
        }
        iMinor = strtol(_argv[4], &pcEnd, 0);
        if (*pcEnd)
        {
            fprintf(stderr, "Bad minor number : %s\n", _argv[4]);
            return 1;
        }
    }

    // ZC: “grep "mkdev" /usr/” 没有查到mkdev的定义...
    //  找到一些信息,说可能在 <sys/mkdev.h>或者<mkdev.h> 中
    //  也又说 用mkdev()换makedev(),于是尝试makedev()...
    //if (mknod(pcPath, iMode, mkdev(iMajor, iMinor)))
    if (mknod(pcPath, iMode, makedev(iMajor, iMinor)))
    {
        fprintf(stderr, "mknod failed : %s\n", strerror(errno));
        return 1;
    }

//    cout << "Hello World!" << endl;
    return 0;
}

 

4、

04_01_sigh :

//#include <iostream>
//using namespace std;

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <sys/time.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <signal.h>

#include <pthread.h>

// ZC: 程序功能:信号处理
// ZC: 由于不知道 如何手动发送SIGHUP信号,于是这个程序不知道如何去测试...
// ZC: 我尝试使用线程执行raise(SIGHUP)的方式,然而 sleep函数 始终 不被打断... ...如何才能打断sleep()函数???

volatile int g_iReopenLog = 0;

void LogString(int _fdLog, char *_pc)
{
    write(_fdLog, _pc, strlen(_pc));
}

void HupHandler(int _iSigNum)
{
    LogString(STDOUT_FILENO, "in function HupHandler()\n");
    g_iReopenLog = 1;
}

void *ThreadFunc(void *)
{
    printf("In function ThreadFunc() - A\n");
    sleep(2);
    raise(SIGHUP);
    printf("In function ThreadFunc() - B\n");
    pthread_exit(NULL);
    //return NULL; // ZC: 这里不需要 return?
}

int main()
{
    int fdLog = STDOUT_FILENO;

    //__sighandler_t
    struct sigaction sa = {0};
    sa.sa_handler = HupHandler;

    int iRtn = sigaction(SIGHUP, &sa, NULL);
    printf("sigaction return value is %d\n", iRtn);
    if (iRtn)
        perror("sigaction");

    pthread_t pthread = 0;
    iRtn = pthread_create(&pthread, NULL, ThreadFunc, NULL);
    if (iRtn)
    {
        perror("pthread_create");
        return 0;
    }

    int iDone = 0;
    while (! iDone)
    {
        int iRtnSleep = sleep(5);// ZC: 这里是 睡眠的秒数 ! ! !
        if (iRtnSleep)
        {
            if (g_iReopenLog)
            {
                LogString(fdLog, "*reopening log files at sighup request \n");
                g_iReopenLog = 0;
            }
            else
            {
                LogString(fdLog, "*sleep interrupted by unknow signal \n");
                iDone = 1;
            }
        }
        else
            LogString(fdLog, "periodic message\n"); // ZC: periodic :周期的,定期的
    }

//    cout << "Hello World!" << endl;
    return 0;
}

 

 

04_02_queued :

//#include <iostream>
//using namespace std;

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <sys/time.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <signal.h>


int g_iNextSig = 0;
int g_iarrSigOrder[10] = {0};

void Handler(int _iSigNum)
{
    printf("In function Handler(), _iSigNum : %d\n", _iSigNum);
    g_iarrSigOrder[g_iNextSig ++] = _iSigNum;
}

int main()
{
    sigset_t sigmask = {0};

    sigemptyset(&sigmask);
    sigaddset(&sigmask, SIGRTMIN);
    sigaddset(&sigmask, SIGRTMIN + 1);
    sigaddset(&sigmask, SIGUSR1);

    struct sigaction sa = {0};
    sa.sa_handler = Handler;
    sa.sa_mask = sigmask;
    sa.sa_flags = 0;

    sigaction(SIGRTMIN, &sa, NULL);
    sigaction(SIGRTMIN + 1, &sa, NULL);
    sigaction(SIGUSR1, &sa, NULL);


    sigset_t sigmaskOld = {0};
    sigprocmask(SIG_BLOCK, &sigmask, &sigmaskOld);
    raise(SIGRTMIN + 1);
    raise(SIGRTMIN);
    raise(SIGRTMIN);
    raise(SIGRTMIN + 1);
    raise(SIGRTMIN);
    raise(SIGUSR1);
    raise(SIGUSR1);

    sigprocmask(SIG_SETMASK, &sigmaskOld, NULL);


    printf("signal received : \n");
    for (int i=0; i<g_iNextSig; i++)
    {
        if (g_iarrSigOrder[i] < SIGRTMIN)
            printf("\t %s \n", strsignal(g_iarrSigOrder[i]));
        else
            printf("\t SIGRTMIN + %d \n", g_iarrSigOrder[i] - SIGRTMIN);
    }

//    cout << "Hello World!" << endl;
    return 0;
}

 

04_03_sicode :

#include <sys/signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

#ifndef SI_TKILL
    #define SI_TKILL    -6
#endif // SI_TKILL

void Handler(int _signo, siginfo_t *_info, void *_f)
{
    static int count = 0;
    printf("[%d] Caught signal sent by ", getpid());
    switch (_info->si_code)
    {
    case SI_USER:
        {
            printf("kill()\n");
            break;
        }
    case SI_QUEUE:
        {
            printf("sigqueue()\n");
            break;
        }
    case SI_TKILL:
        {
            printf("tkill() or raise()\n");
            break;
        }
    case CLD_EXITED:
        {
            printf("kernel telling us child exited\n");
            exit(0);
        }
    }

    if (++count == 4)
    {
        _exit(1);
    }
}

int main()
{
    pid_t pid = getpid();
    printf("Parent process id is %d\n", pid);

    union sigval val;
    val.sival_int = 1234;

    struct sigaction act;
    act.sa_sigaction = Handler;
    sigemptyset(&act.sa_mask);
    act.sa_flags = SA_SIGINFO;
    sigaction(SIGCHLD, &act ,NULL);

    kill(pid, SIGCHLD);
    sigqueue(pid, SIGCHLD, val);
    raise(SIGCHLD);

    if (! fork())
    {
        _exit(0); // ZC: 子进程退出
    }
    sleep(60);
    return 0;
}

 

04_04_catchsig :

#include <sys/signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

void Handler(int _signo, siginfo_t *_info, void *_f)
{
    printf("Cought ");
    if (_info->si_signo == SIGSEGV)
    {
        printf("segv accessing %p\n", _info->si_addr);
    }
    if (_info->si_signo == SEGV_MAPERR)
    {
        printf("segv_maperr\n");
        _exit(1);
    }
}

int main()
{
    struct sigaction act;
    act.sa_sigaction = Handler;
    sigemptyset(&act.sa_mask);
    act.sa_flags = SA_SIGINFO;
    printf("A\n");
    sigaction(SIGSEGV, &act, NULL);
    printf("B\n");
    *((int*)NULL) = 1; // ZC: 认为构建一个写入非法内存异常,会引发什么信号?SIGSEGV
    return 0;
}

 

04_05_sigval :

#include <sys/signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

void Handler(int _signo, siginfo_t *_si, void *_context)
{
    printf("%d\n", _si->_sifields._timer.si_sigval.sival_int);
    printf("%d\n", _si->_sifields._rt.si_sigval.sival_int);
}

int main()
{
    sigset_t oldmask;
    sigset_t mask;
    sigemptyset(&mask);
    sigaddset(&mask, SIGRTMIN);
    sigprocmask(SIG_BLOCK, &mask, &oldmask);

    struct sigaction act;
    act.sa_sigaction = Handler;
    act.sa_mask = mask;
    act.sa_flags = SA_SIGINFO;
    sigaction(SIGRTMIN, &act, NULL);

    int pid = getpid();
    union sigval val;
    val.sival_int = 1;
    sigqueue(pid, SIGRTMIN, val);
    val.sival_int ++;
    sigqueue(pid, SIGRTMIN, val);
    val.sival_int ++;
    sigqueue(pid, SIGRTMIN, val);

    sigprocmask(SIG_SETMASK, &oldmask, NULL);

    return 0;
}

 

5、

05_01_mpxb1 :

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

int main()
{
    int fds[2] = {0};

    if ((fds[0] = open("p1", O_RDONLY)) < 0)
    {
        perror("open p1");
        return 1;
    }

    if ((fds[1] = open("p2", O_RDONLY)) < 0)
    {
        perror("open p2");
        return 1;
    }

    int iIdx = 0;
    while (1)
    {
        char buf[4096];
        int iRead = read(fds[iIdx], buf, sizeof(buf)-1);
        if (iRead < 0)
        {
            perror("read");
            return 1;
        }
        else if (! iRead)
        {
            printf("pipe close\n");
            return 0;
        }
        buf[iRead] = '\0';
        printf("read : %s", buf);
        iIdx = (iIdx + 1) % 2;
    }

}

 

05_02_mpxnob :

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

int main()
{
    int fds[2] = {0};

    if ((fds[0] = open("p1", O_RDONLY | O_NONBLOCK)) < 0)
    {
        perror("open p1");
        return 1;
    }

    if ((fds[1] = open("p2", O_RDONLY | O_NONBLOCK)) < 0)
    {
        perror("open p2");
        return 1;
    }

    int iIdx = 0;
    while (1)
    {
        char buf[4096];
        int iRead = read(fds[iIdx], buf, sizeof(buf)-1);
        if ((iRead < 0) && (errno == EAGAIN))
        {
            perror("read");
            return 1;
        }
        else if (iRead > 0) // 说明已经读取成功了
        {
            buf[iRead] = '\0';
            printf("read : %s", buf);
        }
        // 这里不处理 iRead==0的情况了?

        iIdx = (iIdx + 1) % 2;
    }

}

 

05_03_mpxpoll :

#include <fcntl.h>
#include <stdio.h>
#include <sys/poll.h>
#include <unistd.h>

int main()
{
    struct pollfd fds[2] = {0};

    if (fds[0].fd = open("p1", O_RDONLY | O_NONBLOCK) < 0)
    {
        perror("open p1");
        return 1;
    }

    if (fds[1].fd = open("p2", O_RDONLY | O_NONBLOCK) < 0)
    {
        perror("open p2");
        return 1;
    }

    fds[0].events = POLLIN;
    fds[1].events = POLLIN;

    while (fds[0].events || fds[1].events)
    {
        if (poll(fds, 2, 0))
        {
            perror("poll");
            return 1;
        }

        for (int i=0; i<2; i++)
        {
            if (fds[i].revents)
            {
                char buf[4096] = {0};
                int rc = read(fds[i].fd, buf, sizeof(buf)-1);
                if (rc < 0)
                {
                    perror("read");
                    return 1;
                }
                else if (! rc)
                {
                    fds[i].events = 0;
                }
                else
                {
                    buf[rc] = '\n';
                    printf("read : %s", buf);
                }
            }
        }
    }
    return 0;
}

 

05_04_mpxselect :

#include <fcntl.h>
#include <stdio.h>
#include <sys/select.h>
#include <unistd.h>

int main()
{
    int fds[2] = {0};

    if ((fds[0] = open("p1", O_RDONLY | O_NONBLOCK)) < 0)
    {
        perror("open p1");
        return 1;
    }

    if ((fds[1] = open("p2", O_RDONLY | O_NONBLOCK)) < 0)
    {
        perror("open p2");
        return 1;
    }

    fd_set watchset;
    FD_ZERO(&watchset);
    FD_SET(fds[0], &watchset);
    FD_SET(fds[1], &watchset);

    int maxfd = fds[0] > fds[1] ? fds[0] : fds[1];
    while (FD_ISSET(fds[0], &watchset) || FD_ISSET(fds[1], &watchset))
    {
        fd_set inset = watchset;
        if (select(maxfd+1, &inset, NULL, NULL, NULL) < 0)
        {
            perror("select");
            return 1;
        }
        for (int i=0; i<2; i++)
        {
            if (FD_ISSET(fds[i], &inset))
            {
                char buf[4096] = {0};
                int rc = read(fds[i], buf, sizeof(buf)-1);
                if (rc < 0)
                {
                    perror("read");
                    return 1;
                }
                else if (! rc)
                {
                    close(fds[i]);
                    FD_CLR(fds[i], &watchset);
                }
                else
                {
                    buf[rc] = '\0';
                    printf("read : %s", buf);
                }
            }
        }
    }
    return 0;
}

 

05_05_sepo :

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/select.h>
#include <unistd.h>
#include <sys/signal.h>
#include <sys/poll.h>

int gotalarm;

void CatchZ(int sig)
{
    gotalarm = 1;
}

#define HIGH_FD        1000

int main(int argc, const char **argv)
{
    int devZero;
    int count;
    fd_set selectFds;

    devZero = open("dev/zero", O_RDONLY);
    dup2(devZero, HIGH_FD);
    //signal(SIGARM, CatchZ);
    signal(SIGALRM, CatchZ);

    gotalarm = 0;
    count = 0;
    alarm(1);
    while (! gotalarm)
    {
        FD_ZERO(&selectFds);
        FD_SET(HIGH_FD, &selectFds);
        select(HIGH_FD+1, &selectFds, NULL, NULL, NULL);
        count++;
    }

    printf("select() calls per second : %d\n", count);

    struct pollfd pollfd1;
    pollfd1.fd = HIGH_FD;
    pollfd1.events = POLLIN;
    count = 0;
    gotalarm = 0;
    alarm(1);
    while (! gotalarm)
    {
        poll(&pollfd1, 0, 0);
        count ++;
    }
    printf("poll() calls per second : %d\n", count);
    return 0;
}

 

05_06_epoll :

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/epoll.h>
#include <unistd.h>
#include <sys/poll.h>

void addevent(int wpfd, char *filename)
{
    int fd;
    struct epoll_event event;
    if ((fd = open(filename, O_RDONLY | O_NONBLOCK)) < 0)
    {
        perror("open");
        _exit(1);
    }
    event.events = EPOLLIN;
    event.data.fd= fd;
    if (epoll_ctl(wpfd, EPOLL_CTL_ADD, fd, &event))
    {
        perror("epoll_ctl(ADD)");
        _exit(1);
    }
}

int main()
{
    char buf[4096];
    int i, rc;
    int epfd;
    struct epoll_event events[2];
    int num, numfds;
    epfd = epoll_create(2);
    if (epfd < 0)
    {
        perror("epoll_create");
        return 1;
    }
    addevent(epfd, "p1");
    addevent(epfd, "p2");
    numfds = 2;
    while (numfds)
    {
        if ((num = epoll_wait(epfd, events, sizeof(events)/sizeof(*events), -1)) <= 0)
        {
            perror("epoll_wait");
            return 1;
        }
        for (i=0; i<num; i++)
        {
            rc = read(events[i].data.fd, buf, sizeof(buf)-1);
            if (rc < 0)
            {
                perror("read");
                return 1;
            }
            else if (! rc)
            {
                if (epoll_ctl(epfd, EPOLL_CTL_DEL, events[i].data.fd, &events[i]))
                {
                    perror("epoll_ctl(DEL)");
                    return 1;
                }
                close(events[i].data.fd);
                numfds --;
            }
            else
            {
                buf[rc] = '\0';
                printf("read : %s", buf);
            }
        }
    }
    close(epfd);
    return 0;
}

 

05_07_wrv :

#include <unistd.h>
#include <stdio.h>
#include <sys/uio.h>


int main()
{
    struct iovec buffers[3];
    buffers[0].iov_base = (char*)"hello";
    buffers[0].iov_len = 5;
    buffers[1].iov_base = (char*)"  ";
    buffers[1].iov_len = 2;
    buffers[2].iov_base = (char*)"world\n";
    buffers[2].iov_len = 6;

    write(1, buffers, 3);

    return 0;
}

 

6 、

06_01_dircontent :

#include <errno.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{
    DIR *dir;
    struct dirent *ent;

    if (!(dir = opendir(".")))
    {
        perror("opendir");
        return 1;
    }

    errno = 0;
    while (ent = readdir(dir))
    {
        puts(ent->d_name);
        errno = 0;
    }
    if (errno)
    {
        perror("readdir");
        return 1;
    }
    closedir(dir);
    return 0;
}

 

06_02_pop :

#include <stdio.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>

int main(int argc, const char **argv)
{
    char buf[1024];
    FILE *file;
    int result;
    int i;
    strcpy(buf, "ls");
    for (i=0; i<argc; i++)
    {
        strcat(buf, argv[i]);
        strcat(buf, " ");
    }
    file = popen(buf, "r");
    if (! file)
    {
        perror("popen");
        return 1;
    }
    while (fgets(buf, sizeof(buf),file))
    {
        printf("%s", buf);
    }
    result = pclose(file);
    if (! WIFEXITED(result))
    {
        return 1;
    }
    return 0;
}

 

06_03_glob :

#include <errno.h>
#include <glob.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

int errfn(const char *pathname, int theerr)
{
    fprintf(stderr, "error accessing %s:%s\n", pathname, strerror, theerr);
    return 0;
}


int main(int argc, const char **argv)
{
    glob_t result;
    int i, rc, flags;
    if (argc < 2)
    {
        printf("at least 1 arg\n");
        return 1;
    }
    flags = 0;
    for (i=1; i<argc;i++)
    {
        rc = glob(argv[i], flags, errfn, &result);
        if (rc == GLOB_NOSPACE)
        {
            fprintf(stderr, "out of space\n");
            return 1;
        }
        flags |= GLOB_APPEND;
    }

    if (! result.gl_pathc)
    {
        fprintf(stderr, "no match\n");
        rc = 1;
    }
    else
    {
        for (i=0;i<result.gl_pathc; i++)
        {
            puts(result.gl_pathv[i]);
        }
        rc = 0;
    }
    globfree(&result);
    return rc;
}

 

7、

07_01_server :

#ifndef SOCKUTIL_H
#define SOCKUTIL_H

void die(char *message)
{
    perror(message);
    _exit(1);
}

void copydata(int from, int to)
{
    char buf[1024];
    int amount;
    while ((amount = read(from, buf, sizeof(buf))) > 0)
    {
        if (write(to, buf, amount) != amount)
        {
            die("write");
            return;
        }
    }
    if (amount < 0)
    {
        die("read");
    }
}


#endif // SOCKUTIL_H

 

#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>

#include "sockutil.h"


int main()
{
    struct sockaddr_un address;
    int sock, conn;
    size_t addrlength;

    if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
    {
        die("socket");
    }

    unlink("./sample_socket");

    address.sun_family = AF_UNIX;
    strcpy(address.sun_path, "./sample_socket");

    addrlength = sizeof(address.sun_family) + strlen(address.sun_path);
    if (bind(sock, (struct sockaddr *)&address, addrlength))
    {
        die("bind");
    }

    if (listen(sock, 5))
    {
        die("listen");
    }

    while ((conn = accept(sock, (struct sockaddr *)&address, (socklen_t*)&addrlength)) >= 0)
    {
        printf("---------- getting data ----------\n");
        copydata(conn, 1);
        printf("---------- done ----------\n");
        close(conn);
    }
    if (conn < 0)
    {
        die("accept");
    }
    close(sock);
    return 0;
}

 

07_02_client :

#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <stdio.h>
#include "/home/qt532_projects/201/07_01_server/sockutil.h"

int main()
{
    struct sockaddr_un address;
    int sock;
    size_t addrlength;

    if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
    {
        die("socket");
    }

    address.sun_family = AF_UNIX;
    strcpy(address.sun_path, "./sample_socket");

    addrlength = sizeof(address.sun_family) + strlen(address.sun_path);

    if (connect(sock, (struct sockaddr *)&address, addrlength))
    {
        die("connect");
    }

    copydata(0, sock);
    close(sock);
    return 0;
}

 

07_03_passfd :

#include <alloca.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/uio.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <unistd.h>
#include "/home/qt532_projects/201/07_01_server/sockutil.h"

int childprocess(char *filename, int sock)
{
    int fd;
    struct iovec    vector;
    struct msghdr    msg;
    struct cmsghdr    *cmsg;

    if ((fd = open(filename, O_RDONLY)) < 0)
    {
        perror("open");
        return 1;
    }

    vector.iov_base = filename;
    vector.iov_len = strlen(filename) + 1;

    msg.msg_name = NULL;
    msg.msg_namelen = 0;
    msg.msg_iov = &vector;
    msg.msg_iovlen = 1;

    cmsg = (struct cmsghdr*)alloca(sizeof(struct cmsghdr) + sizeof(fd));
    cmsg->cmsg_len = sizeof(struct cmsghdr) + sizeof(fd);
    cmsg->cmsg_level = SOL_SOCKET;
    cmsg->cmsg_type = SCM_RIGHTS;

    memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));

    msg.msg_control = cmsg;
    msg.msg_controllen = cmsg->cmsg_len;

    if (sendmsg(sock, &msg, 0) != vector.iov_len)
    {
        die("sendmsg");
    }
    return 0;
}

int parentprocess(int sock)
{
    char buf[80];
    struct iovec    vector;
    struct msghdr    msg;
    struct cmsghdr    *cmsg;
    int fd;

    vector.iov_base = buf;
    vector.iov_len = 80;

    msg.msg_name = NULL;
    msg.msg_namelen = 0;
    msg.msg_iov = &vector;
    msg.msg_iovlen = 1;

    cmsg = (struct cmsghdr*)alloca(sizeof(struct cmsghdr) + sizeof(fd));
    cmsg->cmsg_len = sizeof(struct cmsghdr) + sizeof(fd);
    msg.msg_control = cmsg;
    msg.msg_controllen = cmsg->cmsg_len;

    if (! recvmsg(sock, &msg, 0))
    {
        return 1;
    }

    printf("got file descriptor for \"%s\"\n", (char*)vector.iov_base);
    memcpy(&fd, CMSG_DATA(cmsg), sizeof(fd));
    copydata(fd, 1);
    return 0;
}

int main(int argc, const char **argv)
{
    int socks[2];
    int status;

    if (argc != 2)
    {
        fprintf(stderr, "Only a single arg is supported .\n");
        return 1;
    }

    if (socketpair(PF_UNIX, SOCK_STREAM, 0, socks))
    {
        die("socketpair");
    }

    if (! fork())
    {
        close(socks[0]);
        return childprocess((char*)argv[1], socks[1]);
    }

    close(socks[1]);
    parentprocess(socks[0]);

    wait(&status);
    if (WEXITSTATUS(status))
    {
        fprintf(stderr, "child failed\n");
    }
    return 0;
}

 

0703_01_getaddrinfo :

#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main(int argc, const char **argv)
{
    struct addrinfo hints, *addr;
    const char *host = argv[1], *service = argv[2];
    int rc;
    if (argc != 3)
    {
        fprintf(stderr, "exactly two arguments ar needed\n");
        return 1;
    }

    memset(&hints, 0, sizeof(hints));
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_ADDRCONFIG;
    if ((rc = getaddrinfo(host, service, &hints, &addr)))
    {
        fprintf(stderr, "lookup failed\n");
    }
    else
    {
        freeaddrinfo(addr);
    }
    return 0;
}

 

0703_netlookup :

#include <netdb.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <unistd.h>
#include <string.h>

void usage()
{
    fprintf(stderr, "usage : netlookup [--stream][--dgram][--ipv4][--ipv6] [--anme][--udp]\n");
    fprintf(stderr, "                  [--tcp][--cfg][--service <service>][--host <hostname>]\n");
    _exit(1);
}

int main(int argc, const char **argv)
{
    struct addrinfo *addr, *result;
    const char **ptr;
    int rc;
    struct addrinfo hints;
    const char *servicename = NULL;
    const char *hostname = NULL;

    memset(&hints, 0, sizeof(hints));
    ptr = argv + 1;
    while (*ptr && *ptr[0] == '-')
    {
        if (! strcmp(*ptr, "--ipv4"))
            hints.ai_family = PF_INET;
        else if (! strcmp(*ptr, "--ipv6"))
            hints.ai_family = PF_INET6;
        else if (! strcmp(*ptr, "--stream"))
            hints.ai_socktype = SOCK_STREAM;
        else if (! strcmp(*ptr, "--dgram"))
            hints.ai_socktype = SOCK_DGRAM;
        else if (! strcmp(*ptr, "--name"))
            hints.ai_flags |= AI_CANONNAME;
        else if (! strcmp(*ptr, "--cfg"))
            hints.ai_flags |= AI_ADDRCONFIG;
        else if (! strcmp(*ptr, "--tcp"))
            hints.ai_protocol = IPPROTO_TCP;
        else if (! strcmp(*ptr, "--udp"))
            hints.ai_protocol = IPPROTO_UDP;
        else if (! strcmp(*ptr, "--host"))
        {
            ptr ++;
            if (! *ptr)
                usage();
            hostname = *ptr;
        }
        else if (! strcmp(*ptr, "--service"))
        {
            ptr ++;
            if (! *ptr)
                usage();
            servicename = *ptr;
        }
        else
            usage();
        ptr ++;
    }

    if (!hostname && !servicename)
        usage();

    if ((rc = getaddrinfo(hostname, servicename, &hints, &result)))
    {
        fprintf(stderr, "service lookup failed : %s\n", gai_strerror(rc));
        return 1;
    }

    addr = result;
    while (addr)
    {
        switch (addr->ai_family)
        {
        case PF_INET:
            printf("ipv4");
            break;
        case PF_INET6:
            printf("ipv4");
            break;
        default:
            printf("(%d)", addr->ai_family);
            break;
        }

        switch (addr->ai_socktype)
        {
        case SOCK_STREAM:
            printf("\t stream");
            break;
        case SOCK_DGRAM:
            printf("\t dgram");
            break;
        case SOCK_RAW:
            printf("\t raw");
            break;
        default:
            printf("\t (%d)", addr->ai_socktype);
            break;
        }

        if (addr->ai_family == PF_INET || addr->ai_family == PF_INET6)
        {
            switch(addr->ai_protocol)
            {
            case IPPROTO_TCP:
                printf("\t tcp");
                break;
            case IPPROTO_UDP:
                printf("\t udp");
                break;
            case IPPROTO_RAW:
                printf("\t raw");
                break;
            default:
                printf("\t (%d)", addr->ai_protocol);
                break;
            }
        }
        else
            printf("\t");

        if (addr->ai_family == PF_INET)
        {
            struct sockaddr_in *inetaddr = (struct sockaddr_in*)addr->ai_addr;
            char namebuf[INET_ADDRSTRLEN];

            if (servicename)
                printf("\t port %d", ntohs(inetaddr->sin_port));
            if (hostname)
                printf("\t host %s", inet_ntop(AF_INET, &inetaddr->sin_addr, namebuf, sizeof(namebuf)));
        }
        else if (addr->ai_family == PF_INET6)
        {
            struct sockaddr_in6 *inetaddr = (struct sockaddr_in6*)addr->ai_addr;
            char namebuf[INET6_ADDRSTRLEN];

            if (servicename)
                printf("\t port %d", ntohs(inetaddr->sin6_port));
            if (hostname)
                printf("\t host %s", inet_ntop(AF_INET6, &inetaddr->sin6_addr, namebuf, sizeof(namebuf)));
            if (addr->ai_canonname)
                printf("\t name %s", addr->ai_canonname);
        }
        printf("\n");
        addr = addr->ai_next;
    }
    freeaddrinfo(result);
    return 0;
}

 

0704_01_reverselookup :

#include <netdb.h>
#include <arpa/inet.h>
//#include <arppa.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

void usage()
{
    fprintf(stderr, "usage : reverselookup [--numerichost][--numericserv][--namereqd][--udp]\n");
    fprintf(stderr, "                      [--nofqdn][--service <service>][--host <hostname>]\n");
    _exit(1);
}

int main(int argc, const char **argv)
{
    int flags;
    const char *hostaddress = NULL;
    const char *serviceaddress = NULL;
    struct sockaddr_in    addr4;
    struct sockaddr_in6    addr6;

    struct sockaddr *addr = (struct sockaddr *)&addr4;
    int addrlen = sizeof(addr4);

    int rc;
    int portnum = 0;
    const char **ptr;
    char hostname[1024];
    char servicename[256];
    flags = 0;
    ptr = argv + 1;

    while (*ptr && *ptr[0]=='-')
    {
        if (! strcmp(*ptr, "--numerichost"))
            flags |= NI_NUMERICHOST;
        else if (! strcmp(*ptr, "--numericserv"))
            flags |= NI_NUMERICSERV;
        else if (! strcmp(*ptr, "--namereqd"))
            flags |= NI_NAMEREQD;
        else if (! strcmp(*ptr, "--udp"))
            flags |= NI_DGRAM;
        else if (! strcmp(*ptr, "--host"))
        {
            ptr ++;
            if (! *ptr)
                usage();
            hostaddress = *ptr;
        }
        else if (! strcmp(*ptr, "--service"))
        {
            ptr ++;
            if (! *ptr)
                usage();
            serviceaddress = *ptr;
        }
        else
            usage();

        ptr ++;
    }

    if (!hostaddress && !serviceaddress)
        usage();

    if (serviceaddress)
    {
        char *end;
        portnum = htons(strtol(serviceaddress, &end, 0));
        if (*end)
        {
            fprintf(stderr, "failed to convert %s to a number\n", serviceaddress);
            return 1;
        }
    }

    if (! hostaddress)
    {
        addr4.sin_family = AF_INET;
        addr4.sin_port = portnum;
    }
    else if (! strchr(hostaddress, ':'))
    {
        if (inet_pton(AF_INET, hostaddress, &addr4.sin_addr) <= 0)
        {
            fprintf(stderr, "error converting ipv4 address %s\n", hostaddress);
            return 1;
        }
        addr4.sin_family = AF_INET;
        addr4.sin_port = portnum;
    }
    else
    {
        memset(&addr6, 0, sizeof(addr6));
        if (inet_pton(AF_INET6, hostaddress, &addr6.sin6_addr) <= 0)
        {
            fprintf(stderr, "error converting ipv6 address %s\n", hostaddress);
            return 1;
        }
        addr6.sin6_family = AF_INET6;
        addr6.sin6_port = portnum;
        addr = (struct sockaddr *)&addr6;
        addrlen = sizeof(addr6);
    }

    if (! serviceaddress)
        rc = getnameinfo(addr, addrlen, hostname, sizeof(hostname), NULL, 0, flags);
    else if (! hostaddress)
        rc = getnameinfo(addr, addrlen, NULL, 0, servicename, sizeof(servicename), flags);
    else
        rc = getnameinfo(addr, addrlen, hostname, sizeof(hostname), servicename, sizeof(servicename), flags);

    if (rc)
    {
        fprintf(stderr, "reverse lookup failed : %s\n", gai_strerror(rc));
        return 1;
    }

    if (hostaddress)
        printf("hostname : %s\n", hostname);
    if (serviceaddress)
        printf("service name : %s\n", servicename);
    return 0;
}

 

0704_02_tserver :

#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include "/home/qt532_projects/201/07_01_server/sockutil.h"

int main()
{
    int sock, conn, i, rc;
    struct sockaddr address;
    size_t addrlength = sizeof(address);
    struct addrinfo hints, *addr;

    memset(&hints, 0, sizeof(hints));

    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
    if (rc = getaddrinfo(NULL, "4321", &hints, &addr))
    {
        fprintf(stderr, "hostname lookup failed : %s\n", gai_strerror(rc));
        return 1;
    }

    if ((sock = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol)) < 0)
        die("socket");

    i = 1;
    setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));

    if (bind(sock, addr->ai_addr, addr->ai_addrlen))
        die("bind");

    freeaddrinfo(addr);

    if (listen(sock, 5))
        die("listen");

    while ((conn = accept(sock, (struct sockaddr *)&address, (socklen_t*)&addrlength)) >= 0)
    {
        printf("-------------- getting data --------------\n");
        copydata(conn, 1);
        printf("-------------- done --------------\n");
        close(conn);
    }

    if (conn < 0)
    {
        die("accept");
    }
    close(sock);
    return 0;
}

 

0704_03_tclient :

#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include "/home/qt532_projects/201/07_01_server/sockutil.h"

int main(int argc, const char **argv)
{
    struct addrinfo hints, *addr;
    struct sockaddr_in *addrinfo;
    int rc;
    int sock;

    if (argc != 2)
    {
        fprintf(stderr, "Only 1 arg\n");
        return 1;
    }

    memset(&hints, 0, sizeof(hints));

    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_ADDRCONFIG;
    if (rc = getaddrinfo(argv[1], NULL, &hints, &addr))
    {
        fprintf(stderr, "hostname lookup failed : %s\n", gai_strerror(rc));
        return 1;
    }

    addrinfo = (struct sockaddr_in *)addr->ai_addr;
    if ((sock = socket(addrinfo->sin_family, addr->ai_socktype, addr->ai_protocol)) < 0)
        die("socket");

    addrinfo->sin_port = htons(4321);

    if (connect(sock, (struct sockaddr *)addrinfo, addr->ai_addrlen))
        die("connect");

    freeaddrinfo(addr);

    copydata(0, sock);
    close(sock);
    return 0;
}

 

8、

0800_01_gettimeofday :

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <string.h>
#include <ctime>
using namespace std;

int main()
{
    struct timeval    tv;
    struct timezone    tz;

    time_t now;
    // ZC: min time_t value
    time_t beginning_of_time = 1L << (sizeof(time_t)*8 - 1);
    // ZC: max time_t value
    time_t end_of_time = ~beginning_of_time;

    printf("time_t is %u bits long\n\n", sizeof(time_t)*8);
    gettimeofday(&tv, &tz);
    now = tv.tv_sec;

    char carrPrint[1024] = {0};
    strcat(carrPrint, "current time of day represented as a struct timeval :\n");
    strcat(carrPrint, "tv.tv_sec = 0x%08x, tz.tz_usec = 0x%08x\n");
    strcat(carrPrint, "tz.tz_minuteswest = 0x%08x, tz.tz_dsttime = 0x%08x\n\n");
    printf(carrPrint,
           tv.tv_sec, tv.tv_usec,
           tz.tz_minuteswest, tz.tz_dsttime);
    printf("demonstrating ctime() : %s\n", 
        sizeof(time_t)*8 <= 32 ? "" : "(my hang after printing first line; press control-c)");
    printf("time is now %s", ctime(&now));
    printf("time begins %s", ctime(&beginning_of_time));
    printf("time ends %s", ctime(&end_of_time));

    _exit(0);
}

 

0800_02_timer :

#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <sys/time.h>

void catch_signal(int ignored)
{
    static int iteration = 0;
    printf("caught interval timer signal, iteration %d\n", iteration ++);
}

pid_t start_timer(int interval)
{
    pid_t child;
    struct itimerval        it;
    struct sigaction    sa;

    if (!(child = fork()))
    {
        memset(&sa, 0, sizeof(sa));
        sa.sa_handler = catch_signal;
        sa.sa_flags = SA_RESTART;
        sigaction(SIGALRM, &sa, NULL);

        memset(&it, 0, sizeof(it));
        it.it_interval.tv_sec = interval;
        it.it_value.tv_sec = interval;

        setitimer(ITIMER_REAL, &it, NULL);
        while (1)
            pause();
    }
    return child;
}

void stop_timer(pid_t child)
{
    kill(child, SIGTERM);
}

int main(int argc, const char **argv)
{
    pid_t timer = 0;
    printf("demonstrating itimers for 10 seconds, please wait ...\n");

    timer = start_timer(1);
    sleep(10);
    stop_timer(timer);

    printf("done\n");
    return 0;
}

 

9

转载于:https://www.cnblogs.com/LinuxCode/p/5755833.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值