4 * Little hack to let a process run only a specific amount of time. If process
5 * has not finished until that amount of time it is killed.
17 #include <sys/types.h>
21 #define ERR_WRONGARGS -1
24 #define ERR_WAITPID -4
29 void printUsage(FILE* out
, int argc
, char** argv
)
31 fprintf(out
, "Run command <command> for at least a specific time. Kill\n");
32 fprintf(out
, "process executing <command> if time is over. \n");
34 fprintf(out
, "Usage: %s [options] <command>\n", argv
[0]);
36 fprintf(out
, "Options:\n");
37 fprintf(out
, " -h Print this help.\n");
38 fprintf(out
, " -t <sec> Number of seconds.\n");
39 fprintf(out
, " -v Be verbose.\n");
43 int main(int argc
, char** argv
)
47 bool argVerbose
=false;
53 printUsage(stderr
, argc
, argv
);
58 //Get the argument index of the head of <command>
61 //Aha, argument -- skip it
62 while( fiarg
<argc
&& strncmp(argv
[fiarg
], "-", 1)==0 )
65 if( strncmp(argv
[fiarg
], "-h", 2) == 0 )
71 else if( strncmp(argv
[fiarg
], "-t", 2) == 0 )
73 //Time is given -- goto next argument
78 fprintf(stderr
, "Missing time.\n");
79 fprintf(stderr
, "\n");
80 printUsage(stderr
, argc
, argv
);
84 //Convert the time given in seconds to float
86 maxtime
= strtof( argv
[fiarg
], &endptr
);
87 if( endptr
!= argv
[fiarg
] + strlen(argv
[fiarg
]) ||
90 fprintf(stderr
, "Invalid time.\n");
91 fprintf(stderr
, "\n");
92 printUsage(stderr
, argc
, argv
);
98 else if( strncmp(argv
[fiarg
], "-v", 2) == 0 )
107 fprintf(stderr
, "Invalid argument: %s\n", argv
[fiarg
]);
108 fprintf(stderr
, "\n");
109 printUsage(stderr
, argc
, argv
);
110 return ERR_WRONGARGS
;
121 printUsage(stdout
, argc
, argv
);
129 fprintf(stderr
, "No time given!\n");
130 fprintf(stderr
, "\n");
131 printUsage(stderr
, argc
, argv
);
132 return ERR_WRONGARGS
;
138 fprintf(stderr
, "No command given!\n");
139 fprintf(stderr
, "\n");
140 printUsage(stderr
, argc
, argv
);
141 return ERR_WRONGARGS
;
153 char** newargv
= (char**) malloc( sizeof(char*)*(argc
-fiarg
+1) );
154 char* newenv
[] = {NULL
};
157 for( int i
=fiarg
; i
<argc
; i
++)
159 newargv
[i
-fiarg
] = (char*)malloc(strlen(argv
[i
])+1);
160 strcpy(newargv
[i
-fiarg
], argv
[i
]);
162 newargv
[argc
-fiarg
] = NULL
;
165 //Execute child process
166 execve(newargv
[0], newargv
, newenv
);
181 //Nmb of loops=seconds
183 //Status flags of child process
186 const int ussleep
=25000;
191 if( loops
*ussleep
/1e6
>= maxtime
)
194 printf("Kill child...\n");
196 if( kill(pid
, SIGTERM
) < 0)
201 if( waitpid(-1, &status
, WNOHANG
| WUNTRACED
| WCONTINUED
) < 0 )
204 if( WIFEXITED(status
) )
216 printf("Finished\n");