博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
201_Qt5.3.2Code
阅读量:5099 次
发布时间:2019-06-13

本文共 34754 字,大约阅读时间需要 115 分钟。

1、

2、

02_01_getpid : 

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

 

02_04_01_forkd :

#include 
#include
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 
#include
using namespace std;//#include
#include
#include
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 
using namespace std;#include
#include
#include
#include
#include
// 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 
using namespace std;#include
#include
#include
#include
#include
// 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 
using namespace std;#include
#include
#include
#include
#include
#include
#include
#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 
//using namespace std;#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
// 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
//#include
//#include //#include
// ZC: 程序功能:查看显示文件的 Inode flagsint 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 
//using namespace std;#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
//#include
// ZC: 程序功能:模拟 命令mknod的功能 (具体 mknod的用法等概念还是比较模糊 ...)// ZC: 由于 命令"mknod"不太会用,所以 本程序也就没有测试,防止将OS搞坏...void Usage(){ fprintf(stderr, "Usage : mknodexa
[b|c|u|p]
\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的定义... // 找到一些信息,说可能在
或者
中 // 也又说 用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 
//using namespace std;#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
// 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 
//using namespace std;#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
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

 

04_03_sicode :

#include 
#include
#include
#include
#ifndef SI_TKILL #define SI_TKILL -6#endif // SI_TKILLvoid 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 
#include
#include
#include
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 
#include
#include
#include
#include
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 
#include
#include
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 
#include
#include
#include
#include
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 
#include
#include
#include
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 
#include
#include
#include
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 
#include
#include
#include
#include
#include
#include
int gotalarm;void CatchZ(int sig){ gotalarm = 1;}#define HIGH_FD 1000int 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 
#include
#include
#include
#include
#include
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

 

05_07_wrv :

#include 
#include
#include
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 
#include
#include
#include
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 
#include
#include
#include
int main(int argc, const char **argv){ char buf[1024]; FILE *file; int result; int i; strcpy(buf, "ls"); for (i=0; i

 

06_03_glob :

#include 
#include
#include
#include
#include
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

 

7、

07_01_server :

#ifndef SOCKUTIL_H#define SOCKUTIL_Hvoid 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 
#include
#include
#include
#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 
#include
#include
#include
#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 
#include
#include
#include
#include
#include
#include
#include
#include
#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 
#include
#include
#include
#include
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 
#include
#include
#include
#include
#include
#include
#include
void usage(){ fprintf(stderr, "usage : netlookup [--stream][--dgram][--ipv4][--ipv6] [--anme][--udp]\n"); fprintf(stderr, " [--tcp][--cfg][--service
][--host
]\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 
#include
//#include
#include
#include
#include
#include
#include
void usage(){ fprintf(stderr, "usage : reverselookup [--numerichost][--numericserv][--namereqd][--udp]\n"); fprintf(stderr, " [--nofqdn][--service
][--host
]\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 
#include
#include
#include
#include
#include
#include
#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 
#include
#include
#include
#include
#include
#include
#include
#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 
#include
#include
#include
#include
#include
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 
#include
#include
#include
#include
#include
#include
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

你可能感兴趣的文章
Luogu P1463 [HAOI2007]反素数ant:数学 + dfs【反素数】
查看>>
C#中建立treeView
查看>>
hadoop的安装和配置
查看>>
spinnaker
查看>>
hdu 1599 find the mincost route(无向图的最小环)
查看>>
转载:解读CSS布局之-水平垂直居中(2)
查看>>
第十八章 30限制数组越界
查看>>
浅谈unique列上插入重复值的MySQL解决方案
查看>>
hdu 4859(思路题)
查看>>
11.2.0.4 sql*loader/oci direct load导致kpodplck wait before retrying ORA-54
查看>>
sql server 2008空间释放
查看>>
团队-科学计算器-最终总结
查看>>
树的遍历 TJUACM 3988 Password
查看>>
UVA 725 - Division
查看>>
bzoj1798: [Ahoi2009]Seq 维护序列seq(线段树)
查看>>
day5
查看>>
Palindrome
查看>>
窗体中拖动panel,并且不会拖动至窗体外部程序实现方法。
查看>>
vb中从域名得到IP及从IP得到域名
查看>>
一步步跨过学习中一道道的坎
查看>>