#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
//#include
#define GETPTY_BUFSIZE 16
#define READ_BUFSIZE 32
char buffer[READ_BUFSIZE];
int main(int argc,char *argv[])
{
pid_t pid_child;
pid_t rec_pid;
pid_t pid;
int nread;
sigset_t mask;
char *name;
int signo =0;
int err;
int fd;
char tty_name[GETPTY_BUFSIZE];
FILE *f;
char *pidfile = "/var/run/deamon.pid";
sigemptyset(&mask);
sigaddset(&mask, SIGUSR1);
sigprocmask(SIG_SETMASK,&mask,NULL);
// register PON happend
// signal(SIGCHLD, SIG_IGN);
pid = getpid();
if ((f = fopen(pidfile, "w")) == NULL)
{
return -1;
}
fprintf(f, "%d\n", pid);
fclose(f);
fd = open("/dev/ptmx", O_RDWR);
if (fd < 0)
{
printf("open pty error\n");
exit(1);
}
grantpt(fd);
unlockpt(fd);
name = ptsname(fd);
if (!name)
{
printf("ptsname error\n");
exit(1);
}
strncpy(tty_name, name, GETPTY_BUFSIZE);
while(1)
{
do{
err = sigwait(&mask, &signo);
}while(signo !=SIGUSR1 );
//sleep wait for register
sleep(3);
if((pid_child = fork())==-1)
{
printf("Fork Error\n");
exit(1);
}
else if(pid_child > 0) //parent
{
// printf("pid_child %d \n",pid_child);
sleep(6);
write(fd,"exit\n",5);
sleep(3);
rec_pid = waitpid(pid_child,NULL,WNOHANG);
if( rec_pid != pid_child )
{
printf("kill %d \n",pid_child);
kill(pid_child,9);
do{
rec_pid = waitpid(pid_child,NULL,WNOHANG);
}while( rec_pid != pid_child );
}
//clear pty buffer
do
{
nread = read(fd,buffer,READ_BUFSIZE);
}while(nread > 0);
}
else //child
{
/* make new session and process group */
printf("deamon shell\n");
setsid();
fd = open(tty_name, O_RDWR); // becomes our ctty
dup2(fd, 0);
dup2(fd, 1);
dup2(fd, 2);
close(fd);
tcsetpgrp(0, getpid()); // switch this tty's process group to us
//shell
err = execl("/usr/bin/shell","shell",0);
printf("execl %d \n",err);
return 0;
}
}
return 0;
}
阅读(1330) | 评论(0) | 转发(0) |