您的位置:首页 > 运维架构 > Linux

在linux终端写日记

2010-08-05 23:33 375 查看
自己写了个在linux终端像文本写日记的小程序,加入了输入密码,和延时不输入密码退出程序。本人初学,把代码发出来,希望高手们给指点意见 谢谢 下面是代码,经过测试的 大家也可以试下

#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里的出错小函数 ,呵呵 用这几个函数觉得比较方便。 编译好 生成环境变量,以后可以直接用了 呵呵 还是挺方便的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: