在linux终端写日记
2010-08-05 23:33
375 查看
自己写了个在linux终端像文本写日记的小程序,加入了输入密码,和延时不输入密码退出程序。本人初学,把代码发出来,希望高手们给指点意见 谢谢 下面是代码,经过测试的 大家也可以试下
为了能正常的关闭 打开的文件 和 恢复被屏蔽的信号,所以加入了 中断信号 为了跳出中断 正常结束程序。 里面用了几个apue里的出错小函数 ,呵呵 用这几个函数觉得比较方便。 编译好 生成环境变量,以后可以直接用了 呵呵 还是挺方便的
#include "apue.h" #include <signal.h> #include <setjmp.h> #include <fcntl.h> #include <sys/stat.h> #define BUFSIZE 4096 #define LINE 1024 #define pw_ok 2 static jmp_buf al_buf; const char *password="lijunlong";//the answer of password void sig_alarm(int signo) // alarm signal { if(signo==SIGALRM) printf("catch the alarm signal/n"); longjmp(al_buf,1); } void sig_int(int signo) { /******just out of loop*******/ } unsigned char inputpassword(void) { int i=0; char str[LINE]; do{ printf("My name is: "); scanf("%s",str); if(strcmp(str,password)!=0) { printf("password error"); i++; } else { return pw_ok; } } while(i<3);// only have 3 times to input the password err_quit("you have input the wrong password three times!"); } int main() { char buf[BUFSIZE]; int n=0,fd; unsigned char status; sigset_t newmask, oldmask, pendmask; if( signal(SIGALRM,sig_alarm)==SIG_ERR) err_sys("signal error:"); if(signal(SIGINT,sig_int)==SIG_ERR) err_sys("signal error:"); if(setjmp(al_buf)) { err_quit("read time out!"); } alarm(20); // have 20 sec to input the right password if((status=inputpassword())==pw_ok) { alarm(0); sigemptyset(&newmask); sigaddset(&newmask,SIGALRM); if(sigprocmask(SIG_BLOCK,&newmask,&oldmask)<0) //if have right password, block alarm err_sys("sigblock error"); if((fd=open("/home/jldream/mynote",O_RDWR|O_CREAT|O_APPEND,S_IRUSR|S_IWUSR))<0) err_sys("open file error"); system("date >> /home/jldream/mynote"); while((n=read(STDIN_FILENO,buf,BUFSIZE))>0) if(write(fd,buf,n)!=n) err_sys("write err"); close(fd); } if(sigprocmask(SIG_SETMASK,&oldmask,NULL)<0)// reset the mask err_sys("sigsetmask error"); printf("normal exit"); exit(0); }
为了能正常的关闭 打开的文件 和 恢复被屏蔽的信号,所以加入了 中断信号 为了跳出中断 正常结束程序。 里面用了几个apue里的出错小函数 ,呵呵 用这几个函数觉得比较方便。 编译好 生成环境变量,以后可以直接用了 呵呵 还是挺方便的
相关文章推荐
- Linux管理员日记(5) 更简单高效:Linux邮件服务器的安装和安全
- linux终端下,使用ls时,显示的文件颜色,都表示什么含义,在哪里可以查看和修改
- 个人总结日记:ltv350三星LCD并行接口接2440处理器的linux驱动程序移植
- linux 如何杀掉 tty终端
- linux终端乱码解决方法
- 基于Linux命令行终端的ftp客户端程序
- 改变linux终端颜色 关闭警铃 xset b off
- Linux 终端 Bash 常用快捷键介绍及经验
- SVR4/4.3BSD与Linux对待伪终端的不同方式
- Linux终端快捷键
- 几个linux终端的有趣玩法
- 重启和关闭 Linux 系统的 6 个终端命令
- Linux Serial console Linux串口终端配置 无显卡启动
- Linux上的超级终端 kermit
- 解决Linux关闭终端(关闭SSH等)后运行的程序或者服务自动停止【后台运行程序】
- (工具类)Linux笔记之终端日志记录工具script
- ubuntu/Linux终端shell配置代理 | git 配置代理
- MacBook终端远程连接Linux
- Emacs在linux终端上输入backspace的问题
- 终端中的乐趣:6个有趣的Linux命令行工具