|
因为共享网线,一挂电驴,全网瘫痪,所以只能挑夜间无人上网时才挂电驴。但挂一定时间后,需自动结束电驴进程,以免有人起来后上网,你的电驴还挂着,同样影响别人的利益。所以,程序的功能是:自定义要启动的程序名称,自定义程序启动时间,自定义关闭程序时间。在程序里,只要输入程序的名字即可运行(但没有处理绝对路径,相对路径这些情况,只支持标准路径里的程序)。
实现代码如下:
#include <time.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#define NAME_SIZE 256
char name_buffer[NAME_SIZE];
int start_hour;
int start_minute;
int stop_hour;
int stop_minute;
struct tm *tm_ptr;
int main()
{
pid_t pid;
time_t the_time;
char command [64];
char appid [64];
int id;
FILE *fd;
printf ("请输入程序启动时间(小时):");
scanf ("%d", &start_hour);
if (start_hour > 24 || start_hour < 0) {
printf ("输入小时错误!\n");
exit (1);
}
printf ("\n");
printf ("请输入程序启动时间(分钟):");
scanf ("%d", &start_minute);
if (start_minute > 59 || start_minute < 0) {
printf ("输入分钟错误!\n");
exit (1);
}
printf ("\n");
printf ("请输入程序停止时间(小时):");
scanf ("%d", &stop_hour);
if (stop_hour > 24 || stop_hour < 0) {
printf ("输入小时错误!\n");
exit (1);
}
printf ("\n");
printf ("请输入程序停止时间(分钟):");
scanf ("%d", &stop_minute);
if (stop_minute > 59 || stop_minute < 0) {
printf ("输入分钟错误!\n");
exit (1);
}
printf ("\n");
printf ("请输入要启动程序的名称:");
scanf ("%s", name_buffer);
name_buffer [sizeof (name_buffer) - 1] ='\0';
printf ("要启动的程序为: %s", name_buffer);
printf ("\n");
while (1) {
time (&the_time);
tm_ptr = gmtime (&the_time);
printf ("当前时间: %02d:%02d:%02d\n", tm_ptr->tm_hour + 8, tm_ptr->tm_min, tm_ptr->tm_sec);
if ((tm_ptr->tm_hour + 8) == start_hour && tm_ptr->tm_min == start_minute)
break;
sleep (1);
}
pid = fork();
switch (pid) {
case -1:
perror ("fork failed");
exit (1);
case 0:
system (name_buffer);
break;
default:
while (1) {
(void) time (&the_time);
tm_ptr = gmtime (&the_time);
if ((tm_ptr->tm_hour + 8) == stop_hour && tm_ptr->tm_min == stop_minute)
break;
sleep (1);
}
sprintf (command, "ps -A -o pid,comm |grep %s |awk '{print $1}'", name_buffer);
if ((fd = popen (command, "r")) == NULL) {
perror ("popen");
exit (EXIT_FAILURE);
}
fgets (appid, 64, fd);
id = atoi (appid);
if (kill (id, SIGKILL) == -1) {
perror ("kill");
exit (EXIT_FAILURE);
}
break;
}
exit (0);
} |
|