Killing a process once time limit exceeded
I've been working on the following code for quite some time, but can't really figure it out.
The task is to read a terminal command and to run it every x seconds; if the command hasn't finished within the waiting time, we want to kill the process and afterwards run the command again.
Any help would be really appreciated.
I'm pretty sure I'm not using waitpid() correctly; how would I go about using waitpid to achieve the goal?
Additionally, how would I go about detecting an error within a child process? The plan is to kill the parent process if an error occurred in a child process.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
/*
*
*/
int main(int argc, char** argv) {
int waitingTime;
if (argc < 3) {
printf("Invalid number of arguments provided. Please specify a command and exactly one parameter.");
return (EXIT_FAILURE);
}
// -n parameter specified? If so, set the waiting time.
if (argc == 5 && strcmp(argv[3], "-n") == 0) {
waitingTime = atoi(argv[4]);
} else {
waitingTime = 5; // Default waiting time.
}
char* cmd = (char*)malloc(sizeof(argv[1]));
cmd = argv[1];
char* param = (char*)malloc(sizeof(argv[2]));
param = argv[2];
// Print the read command and its param
printf("Command: %s, Parameter: %s, Interval: %dnn", cmd, param, waitingTime);
pid_t pid;
for (;;) {
// Declared here for scope
int secsWaited;
secsWaited = 0;
pid = fork();
if (pid == 0) {
pid = getpid();
printf("==============n");
execlp(cmd, cmd, param, "/", (char *)NULL);
printf("Excec failed; killing the proccess.");
kill(pid, SIGKILL);
} else if (pid > 0) {
int status, code;
for (;;) {
code = waitpid(pid, &status, WNOHANG);
if (code == 0 && secsWaited >= waitingTime) {
kill(pid, SIGKILL);
printf("Child stopped");
break;
} else if (code == 0 && secsWaited < waitingTime) {
secsWaited++;
sleep(1);
} else {
break;
}
}
/*if (!WIFEXITED(status)) {
printf("Time exceeding, stopping child.");
// Get parent process id and kill it.
kill(getpid(), SIGKILL);
}*/
// Sleep for the specified time
sleep(waitingTime - secsWaited);
} else {
return (EXIT_FAILURE);
}
}
free(cmd);
free(param);
return (EXIT_SUCCESS);
}
c kill-process waitpid
add a comment |
I've been working on the following code for quite some time, but can't really figure it out.
The task is to read a terminal command and to run it every x seconds; if the command hasn't finished within the waiting time, we want to kill the process and afterwards run the command again.
Any help would be really appreciated.
I'm pretty sure I'm not using waitpid() correctly; how would I go about using waitpid to achieve the goal?
Additionally, how would I go about detecting an error within a child process? The plan is to kill the parent process if an error occurred in a child process.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
/*
*
*/
int main(int argc, char** argv) {
int waitingTime;
if (argc < 3) {
printf("Invalid number of arguments provided. Please specify a command and exactly one parameter.");
return (EXIT_FAILURE);
}
// -n parameter specified? If so, set the waiting time.
if (argc == 5 && strcmp(argv[3], "-n") == 0) {
waitingTime = atoi(argv[4]);
} else {
waitingTime = 5; // Default waiting time.
}
char* cmd = (char*)malloc(sizeof(argv[1]));
cmd = argv[1];
char* param = (char*)malloc(sizeof(argv[2]));
param = argv[2];
// Print the read command and its param
printf("Command: %s, Parameter: %s, Interval: %dnn", cmd, param, waitingTime);
pid_t pid;
for (;;) {
// Declared here for scope
int secsWaited;
secsWaited = 0;
pid = fork();
if (pid == 0) {
pid = getpid();
printf("==============n");
execlp(cmd, cmd, param, "/", (char *)NULL);
printf("Excec failed; killing the proccess.");
kill(pid, SIGKILL);
} else if (pid > 0) {
int status, code;
for (;;) {
code = waitpid(pid, &status, WNOHANG);
if (code == 0 && secsWaited >= waitingTime) {
kill(pid, SIGKILL);
printf("Child stopped");
break;
} else if (code == 0 && secsWaited < waitingTime) {
secsWaited++;
sleep(1);
} else {
break;
}
}
/*if (!WIFEXITED(status)) {
printf("Time exceeding, stopping child.");
// Get parent process id and kill it.
kill(getpid(), SIGKILL);
}*/
// Sleep for the specified time
sleep(waitingTime - secsWaited);
} else {
return (EXIT_FAILURE);
}
}
free(cmd);
free(param);
return (EXIT_SUCCESS);
}
c kill-process waitpid
any particular reason you're using C for this? Such a task would be much better suited for shell programming or higher level programming languages like python.
– YoYoYonnY
Nov 20 '18 at 23:27
I'm asked to do it in C, it wasn't my idea.
– ximilianL
Nov 20 '18 at 23:34
add a comment |
I've been working on the following code for quite some time, but can't really figure it out.
The task is to read a terminal command and to run it every x seconds; if the command hasn't finished within the waiting time, we want to kill the process and afterwards run the command again.
Any help would be really appreciated.
I'm pretty sure I'm not using waitpid() correctly; how would I go about using waitpid to achieve the goal?
Additionally, how would I go about detecting an error within a child process? The plan is to kill the parent process if an error occurred in a child process.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
/*
*
*/
int main(int argc, char** argv) {
int waitingTime;
if (argc < 3) {
printf("Invalid number of arguments provided. Please specify a command and exactly one parameter.");
return (EXIT_FAILURE);
}
// -n parameter specified? If so, set the waiting time.
if (argc == 5 && strcmp(argv[3], "-n") == 0) {
waitingTime = atoi(argv[4]);
} else {
waitingTime = 5; // Default waiting time.
}
char* cmd = (char*)malloc(sizeof(argv[1]));
cmd = argv[1];
char* param = (char*)malloc(sizeof(argv[2]));
param = argv[2];
// Print the read command and its param
printf("Command: %s, Parameter: %s, Interval: %dnn", cmd, param, waitingTime);
pid_t pid;
for (;;) {
// Declared here for scope
int secsWaited;
secsWaited = 0;
pid = fork();
if (pid == 0) {
pid = getpid();
printf("==============n");
execlp(cmd, cmd, param, "/", (char *)NULL);
printf("Excec failed; killing the proccess.");
kill(pid, SIGKILL);
} else if (pid > 0) {
int status, code;
for (;;) {
code = waitpid(pid, &status, WNOHANG);
if (code == 0 && secsWaited >= waitingTime) {
kill(pid, SIGKILL);
printf("Child stopped");
break;
} else if (code == 0 && secsWaited < waitingTime) {
secsWaited++;
sleep(1);
} else {
break;
}
}
/*if (!WIFEXITED(status)) {
printf("Time exceeding, stopping child.");
// Get parent process id and kill it.
kill(getpid(), SIGKILL);
}*/
// Sleep for the specified time
sleep(waitingTime - secsWaited);
} else {
return (EXIT_FAILURE);
}
}
free(cmd);
free(param);
return (EXIT_SUCCESS);
}
c kill-process waitpid
I've been working on the following code for quite some time, but can't really figure it out.
The task is to read a terminal command and to run it every x seconds; if the command hasn't finished within the waiting time, we want to kill the process and afterwards run the command again.
Any help would be really appreciated.
I'm pretty sure I'm not using waitpid() correctly; how would I go about using waitpid to achieve the goal?
Additionally, how would I go about detecting an error within a child process? The plan is to kill the parent process if an error occurred in a child process.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
/*
*
*/
int main(int argc, char** argv) {
int waitingTime;
if (argc < 3) {
printf("Invalid number of arguments provided. Please specify a command and exactly one parameter.");
return (EXIT_FAILURE);
}
// -n parameter specified? If so, set the waiting time.
if (argc == 5 && strcmp(argv[3], "-n") == 0) {
waitingTime = atoi(argv[4]);
} else {
waitingTime = 5; // Default waiting time.
}
char* cmd = (char*)malloc(sizeof(argv[1]));
cmd = argv[1];
char* param = (char*)malloc(sizeof(argv[2]));
param = argv[2];
// Print the read command and its param
printf("Command: %s, Parameter: %s, Interval: %dnn", cmd, param, waitingTime);
pid_t pid;
for (;;) {
// Declared here for scope
int secsWaited;
secsWaited = 0;
pid = fork();
if (pid == 0) {
pid = getpid();
printf("==============n");
execlp(cmd, cmd, param, "/", (char *)NULL);
printf("Excec failed; killing the proccess.");
kill(pid, SIGKILL);
} else if (pid > 0) {
int status, code;
for (;;) {
code = waitpid(pid, &status, WNOHANG);
if (code == 0 && secsWaited >= waitingTime) {
kill(pid, SIGKILL);
printf("Child stopped");
break;
} else if (code == 0 && secsWaited < waitingTime) {
secsWaited++;
sleep(1);
} else {
break;
}
}
/*if (!WIFEXITED(status)) {
printf("Time exceeding, stopping child.");
// Get parent process id and kill it.
kill(getpid(), SIGKILL);
}*/
// Sleep for the specified time
sleep(waitingTime - secsWaited);
} else {
return (EXIT_FAILURE);
}
}
free(cmd);
free(param);
return (EXIT_SUCCESS);
}
c kill-process waitpid
c kill-process waitpid
asked Nov 20 '18 at 23:23
ximilianLximilianL
132
132
any particular reason you're using C for this? Such a task would be much better suited for shell programming or higher level programming languages like python.
– YoYoYonnY
Nov 20 '18 at 23:27
I'm asked to do it in C, it wasn't my idea.
– ximilianL
Nov 20 '18 at 23:34
add a comment |
any particular reason you're using C for this? Such a task would be much better suited for shell programming or higher level programming languages like python.
– YoYoYonnY
Nov 20 '18 at 23:27
I'm asked to do it in C, it wasn't my idea.
– ximilianL
Nov 20 '18 at 23:34
any particular reason you're using C for this? Such a task would be much better suited for shell programming or higher level programming languages like python.
– YoYoYonnY
Nov 20 '18 at 23:27
any particular reason you're using C for this? Such a task would be much better suited for shell programming or higher level programming languages like python.
– YoYoYonnY
Nov 20 '18 at 23:27
I'm asked to do it in C, it wasn't my idea.
– ximilianL
Nov 20 '18 at 23:34
I'm asked to do it in C, it wasn't my idea.
– ximilianL
Nov 20 '18 at 23:34
add a comment |
1 Answer
1
active
oldest
votes
Your logic was a bit too complicated (e.g. too many different sleep
calls and if/else
ladder logic).
Also, no need to malloc
the argv
strings--they can be used directly.
I've simplified it and restructured a bit to get it to work [please pardon the gratuitous style cleanup]:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
/*
*
*/
int
main(int argc, char **argv)
{
int waitingTime;
if (argc < 3) {
printf("Invalid number of arguments provided. Please specify a command and exactly one parameter.");
return (EXIT_FAILURE);
}
// -n parameter specified? If so, set the waiting time.
if (argc == 5 && strcmp(argv[3], "-n") == 0) {
waitingTime = atoi(argv[4]);
}
else {
waitingTime = 5; // Default waiting time.
}
char *cmd = argv[1];
char *param = argv[2];
// Print the read command and its param
printf("Command: %s, Parameter: %s, Interval: %dnn",
cmd, param, waitingTime);
pid_t pid;
int code = -1;
int status;
int killflg = 1;
for (;;) {
// Declared here for scope
int secsWaited;
secsWaited = 0;
pid = fork();
// stop on fork failure
if (pid < 0) {
killflg = 1;
break;
}
// child process
if (pid == 0) {
pid = getpid();
printf("==============n");
#if 0
execlp(cmd, cmd, param, "/", (char *) NULL);
#else
execlp(cmd, cmd, param, (char *) NULL);
#endif
printf("Excec failed; killing the proccess.");
// NOTE/BUG: this is the child so pid is zero, so killing it is wrong
#if 0
kill(pid, SIGKILL);
#else
exit(1);
#endif
}
killflg = 0;
for (;;) {
code = waitpid(pid, &status, WNOHANG);
if (code > 0)
break;
if (killflg)
continue;
secsWaited++;
sleep(1);
if (secsWaited >= waitingTime) {
printf("timeoutn");
kill(pid, SIGKILL);
killflg = 1;
}
}
if (! killflg)
break;
}
#if 0
free(cmd);
free(param);
#endif
if (killflg)
code = EXIT_FAILURE;
else
code = EXIT_SUCCESS;
return code;
}
UPDATE:
Right now, the program will stop after one iteration; if I remove the breakpoint at
if (! killflg)
, it will work as expected. Am I missing something or is this just a misunderstanding?
You are correct--my bad. I had missed the following in your question:
The task is to read a terminal command and to run it every x seconds;
Change the break
into sleep(waitingTime - secsWaited)
.
But, a more robust way to keep track of elapsed time may be via two calls to time(2)
:
After the killflg = 0
, do: time_t todbeg = time(NULL); time_t todelap;
. Then, you can get elapsed time [anywhere] with: todelap = time(NULL) - todbeg;
[here, todelap
is similar to secsWaited
]. This may be better than incrementing secsWaited
.
time
only has seconds resolution. For more precision control, consider using clock_gettime
[has nanosecond resolution].
Here's a function that I use a lot for elapsed time [in fractional seconds]:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
#include <time.h>
double
tvgetf(void)
{
struct timespec ts;
double sec;
clock_gettime(CLOCK_REALTIME,&ts);
sec = ts.tv_nsec;
sec /= 1e9;
sec += ts.tv_sec;
return sec;
}
/*
*
*/
int
main(int argc, char **argv)
{
int waitingTime;
if (argc < 3) {
printf("Invalid number of arguments provided. Please specify a command and exactly one parameter.");
return (EXIT_FAILURE);
}
// -n parameter specified? If so, set the waiting time.
if (argc == 5 && strcmp(argv[3], "-n") == 0) {
waitingTime = atoi(argv[4]);
}
else {
waitingTime = 5; // Default waiting time.
}
char *cmd = argv[1];
char *param = argv[2];
// Print the read command and its param
printf("Command: %s, Parameter: %s, Interval: %dnn", cmd, param, waitingTime);
pid_t pid;
int code = -1;
int status;
int killflg = 1;
double todzero = tvgetf();
for (;;) {
// Declared here for scope
double todbeg = tvgetf();
double todelap;
pid = fork();
// stop on fork failure
if (pid < 0) {
killflg = 1;
break;
}
// child process
if (pid == 0) {
pid = getpid();
printf("============== (%.9f)n",tvgetf() - todzero);
execlp(cmd, cmd, param, (char *) NULL);
printf("Excec failed; killing the proccess.");
exit(1);
}
killflg = 0;
for (;;) {
code = waitpid(pid, &status, WNOHANG);
if (code > 0)
break;
if (killflg)
continue;
usleep(1000);
todelap = tvgetf() - todbeg;
if (todelap >= waitingTime) {
printf("timeoutn");
kill(pid, SIGKILL);
killflg = 1;
}
}
// do _not_ wait -- we already timed out
if (killflg)
continue;
// get final elapsed time for this round and the amount of time
// remaining until the next interval
todelap = tvgetf() - todbeg;
useconds_t time_to_wait = ((double) waitingTime - todelap) * 1e6;
// wait until the next time period
if (time_to_wait > 0)
usleep(time_to_wait);
}
if (killflg)
code = EXIT_FAILURE;
else
code = EXIT_SUCCESS;
return code;
}
Side note: I used usleep
here, but, although slightly more complex, it's considered better to use nanosleep
Okay, that makes sense and helped me understand the related commands. However, I do have one question left: Right now, the program will stop after one iteration; if I remove the breakpoint at "if ( !killflg)", it will work as expected. Am I missing something or is this just a misunderstanding?
– ximilianL
Nov 21 '18 at 0:55
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53403120%2fkilling-a-process-once-time-limit-exceeded%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Your logic was a bit too complicated (e.g. too many different sleep
calls and if/else
ladder logic).
Also, no need to malloc
the argv
strings--they can be used directly.
I've simplified it and restructured a bit to get it to work [please pardon the gratuitous style cleanup]:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
/*
*
*/
int
main(int argc, char **argv)
{
int waitingTime;
if (argc < 3) {
printf("Invalid number of arguments provided. Please specify a command and exactly one parameter.");
return (EXIT_FAILURE);
}
// -n parameter specified? If so, set the waiting time.
if (argc == 5 && strcmp(argv[3], "-n") == 0) {
waitingTime = atoi(argv[4]);
}
else {
waitingTime = 5; // Default waiting time.
}
char *cmd = argv[1];
char *param = argv[2];
// Print the read command and its param
printf("Command: %s, Parameter: %s, Interval: %dnn",
cmd, param, waitingTime);
pid_t pid;
int code = -1;
int status;
int killflg = 1;
for (;;) {
// Declared here for scope
int secsWaited;
secsWaited = 0;
pid = fork();
// stop on fork failure
if (pid < 0) {
killflg = 1;
break;
}
// child process
if (pid == 0) {
pid = getpid();
printf("==============n");
#if 0
execlp(cmd, cmd, param, "/", (char *) NULL);
#else
execlp(cmd, cmd, param, (char *) NULL);
#endif
printf("Excec failed; killing the proccess.");
// NOTE/BUG: this is the child so pid is zero, so killing it is wrong
#if 0
kill(pid, SIGKILL);
#else
exit(1);
#endif
}
killflg = 0;
for (;;) {
code = waitpid(pid, &status, WNOHANG);
if (code > 0)
break;
if (killflg)
continue;
secsWaited++;
sleep(1);
if (secsWaited >= waitingTime) {
printf("timeoutn");
kill(pid, SIGKILL);
killflg = 1;
}
}
if (! killflg)
break;
}
#if 0
free(cmd);
free(param);
#endif
if (killflg)
code = EXIT_FAILURE;
else
code = EXIT_SUCCESS;
return code;
}
UPDATE:
Right now, the program will stop after one iteration; if I remove the breakpoint at
if (! killflg)
, it will work as expected. Am I missing something or is this just a misunderstanding?
You are correct--my bad. I had missed the following in your question:
The task is to read a terminal command and to run it every x seconds;
Change the break
into sleep(waitingTime - secsWaited)
.
But, a more robust way to keep track of elapsed time may be via two calls to time(2)
:
After the killflg = 0
, do: time_t todbeg = time(NULL); time_t todelap;
. Then, you can get elapsed time [anywhere] with: todelap = time(NULL) - todbeg;
[here, todelap
is similar to secsWaited
]. This may be better than incrementing secsWaited
.
time
only has seconds resolution. For more precision control, consider using clock_gettime
[has nanosecond resolution].
Here's a function that I use a lot for elapsed time [in fractional seconds]:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
#include <time.h>
double
tvgetf(void)
{
struct timespec ts;
double sec;
clock_gettime(CLOCK_REALTIME,&ts);
sec = ts.tv_nsec;
sec /= 1e9;
sec += ts.tv_sec;
return sec;
}
/*
*
*/
int
main(int argc, char **argv)
{
int waitingTime;
if (argc < 3) {
printf("Invalid number of arguments provided. Please specify a command and exactly one parameter.");
return (EXIT_FAILURE);
}
// -n parameter specified? If so, set the waiting time.
if (argc == 5 && strcmp(argv[3], "-n") == 0) {
waitingTime = atoi(argv[4]);
}
else {
waitingTime = 5; // Default waiting time.
}
char *cmd = argv[1];
char *param = argv[2];
// Print the read command and its param
printf("Command: %s, Parameter: %s, Interval: %dnn", cmd, param, waitingTime);
pid_t pid;
int code = -1;
int status;
int killflg = 1;
double todzero = tvgetf();
for (;;) {
// Declared here for scope
double todbeg = tvgetf();
double todelap;
pid = fork();
// stop on fork failure
if (pid < 0) {
killflg = 1;
break;
}
// child process
if (pid == 0) {
pid = getpid();
printf("============== (%.9f)n",tvgetf() - todzero);
execlp(cmd, cmd, param, (char *) NULL);
printf("Excec failed; killing the proccess.");
exit(1);
}
killflg = 0;
for (;;) {
code = waitpid(pid, &status, WNOHANG);
if (code > 0)
break;
if (killflg)
continue;
usleep(1000);
todelap = tvgetf() - todbeg;
if (todelap >= waitingTime) {
printf("timeoutn");
kill(pid, SIGKILL);
killflg = 1;
}
}
// do _not_ wait -- we already timed out
if (killflg)
continue;
// get final elapsed time for this round and the amount of time
// remaining until the next interval
todelap = tvgetf() - todbeg;
useconds_t time_to_wait = ((double) waitingTime - todelap) * 1e6;
// wait until the next time period
if (time_to_wait > 0)
usleep(time_to_wait);
}
if (killflg)
code = EXIT_FAILURE;
else
code = EXIT_SUCCESS;
return code;
}
Side note: I used usleep
here, but, although slightly more complex, it's considered better to use nanosleep
Okay, that makes sense and helped me understand the related commands. However, I do have one question left: Right now, the program will stop after one iteration; if I remove the breakpoint at "if ( !killflg)", it will work as expected. Am I missing something or is this just a misunderstanding?
– ximilianL
Nov 21 '18 at 0:55
add a comment |
Your logic was a bit too complicated (e.g. too many different sleep
calls and if/else
ladder logic).
Also, no need to malloc
the argv
strings--they can be used directly.
I've simplified it and restructured a bit to get it to work [please pardon the gratuitous style cleanup]:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
/*
*
*/
int
main(int argc, char **argv)
{
int waitingTime;
if (argc < 3) {
printf("Invalid number of arguments provided. Please specify a command and exactly one parameter.");
return (EXIT_FAILURE);
}
// -n parameter specified? If so, set the waiting time.
if (argc == 5 && strcmp(argv[3], "-n") == 0) {
waitingTime = atoi(argv[4]);
}
else {
waitingTime = 5; // Default waiting time.
}
char *cmd = argv[1];
char *param = argv[2];
// Print the read command and its param
printf("Command: %s, Parameter: %s, Interval: %dnn",
cmd, param, waitingTime);
pid_t pid;
int code = -1;
int status;
int killflg = 1;
for (;;) {
// Declared here for scope
int secsWaited;
secsWaited = 0;
pid = fork();
// stop on fork failure
if (pid < 0) {
killflg = 1;
break;
}
// child process
if (pid == 0) {
pid = getpid();
printf("==============n");
#if 0
execlp(cmd, cmd, param, "/", (char *) NULL);
#else
execlp(cmd, cmd, param, (char *) NULL);
#endif
printf("Excec failed; killing the proccess.");
// NOTE/BUG: this is the child so pid is zero, so killing it is wrong
#if 0
kill(pid, SIGKILL);
#else
exit(1);
#endif
}
killflg = 0;
for (;;) {
code = waitpid(pid, &status, WNOHANG);
if (code > 0)
break;
if (killflg)
continue;
secsWaited++;
sleep(1);
if (secsWaited >= waitingTime) {
printf("timeoutn");
kill(pid, SIGKILL);
killflg = 1;
}
}
if (! killflg)
break;
}
#if 0
free(cmd);
free(param);
#endif
if (killflg)
code = EXIT_FAILURE;
else
code = EXIT_SUCCESS;
return code;
}
UPDATE:
Right now, the program will stop after one iteration; if I remove the breakpoint at
if (! killflg)
, it will work as expected. Am I missing something or is this just a misunderstanding?
You are correct--my bad. I had missed the following in your question:
The task is to read a terminal command and to run it every x seconds;
Change the break
into sleep(waitingTime - secsWaited)
.
But, a more robust way to keep track of elapsed time may be via two calls to time(2)
:
After the killflg = 0
, do: time_t todbeg = time(NULL); time_t todelap;
. Then, you can get elapsed time [anywhere] with: todelap = time(NULL) - todbeg;
[here, todelap
is similar to secsWaited
]. This may be better than incrementing secsWaited
.
time
only has seconds resolution. For more precision control, consider using clock_gettime
[has nanosecond resolution].
Here's a function that I use a lot for elapsed time [in fractional seconds]:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
#include <time.h>
double
tvgetf(void)
{
struct timespec ts;
double sec;
clock_gettime(CLOCK_REALTIME,&ts);
sec = ts.tv_nsec;
sec /= 1e9;
sec += ts.tv_sec;
return sec;
}
/*
*
*/
int
main(int argc, char **argv)
{
int waitingTime;
if (argc < 3) {
printf("Invalid number of arguments provided. Please specify a command and exactly one parameter.");
return (EXIT_FAILURE);
}
// -n parameter specified? If so, set the waiting time.
if (argc == 5 && strcmp(argv[3], "-n") == 0) {
waitingTime = atoi(argv[4]);
}
else {
waitingTime = 5; // Default waiting time.
}
char *cmd = argv[1];
char *param = argv[2];
// Print the read command and its param
printf("Command: %s, Parameter: %s, Interval: %dnn", cmd, param, waitingTime);
pid_t pid;
int code = -1;
int status;
int killflg = 1;
double todzero = tvgetf();
for (;;) {
// Declared here for scope
double todbeg = tvgetf();
double todelap;
pid = fork();
// stop on fork failure
if (pid < 0) {
killflg = 1;
break;
}
// child process
if (pid == 0) {
pid = getpid();
printf("============== (%.9f)n",tvgetf() - todzero);
execlp(cmd, cmd, param, (char *) NULL);
printf("Excec failed; killing the proccess.");
exit(1);
}
killflg = 0;
for (;;) {
code = waitpid(pid, &status, WNOHANG);
if (code > 0)
break;
if (killflg)
continue;
usleep(1000);
todelap = tvgetf() - todbeg;
if (todelap >= waitingTime) {
printf("timeoutn");
kill(pid, SIGKILL);
killflg = 1;
}
}
// do _not_ wait -- we already timed out
if (killflg)
continue;
// get final elapsed time for this round and the amount of time
// remaining until the next interval
todelap = tvgetf() - todbeg;
useconds_t time_to_wait = ((double) waitingTime - todelap) * 1e6;
// wait until the next time period
if (time_to_wait > 0)
usleep(time_to_wait);
}
if (killflg)
code = EXIT_FAILURE;
else
code = EXIT_SUCCESS;
return code;
}
Side note: I used usleep
here, but, although slightly more complex, it's considered better to use nanosleep
Okay, that makes sense and helped me understand the related commands. However, I do have one question left: Right now, the program will stop after one iteration; if I remove the breakpoint at "if ( !killflg)", it will work as expected. Am I missing something or is this just a misunderstanding?
– ximilianL
Nov 21 '18 at 0:55
add a comment |
Your logic was a bit too complicated (e.g. too many different sleep
calls and if/else
ladder logic).
Also, no need to malloc
the argv
strings--they can be used directly.
I've simplified it and restructured a bit to get it to work [please pardon the gratuitous style cleanup]:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
/*
*
*/
int
main(int argc, char **argv)
{
int waitingTime;
if (argc < 3) {
printf("Invalid number of arguments provided. Please specify a command and exactly one parameter.");
return (EXIT_FAILURE);
}
// -n parameter specified? If so, set the waiting time.
if (argc == 5 && strcmp(argv[3], "-n") == 0) {
waitingTime = atoi(argv[4]);
}
else {
waitingTime = 5; // Default waiting time.
}
char *cmd = argv[1];
char *param = argv[2];
// Print the read command and its param
printf("Command: %s, Parameter: %s, Interval: %dnn",
cmd, param, waitingTime);
pid_t pid;
int code = -1;
int status;
int killflg = 1;
for (;;) {
// Declared here for scope
int secsWaited;
secsWaited = 0;
pid = fork();
// stop on fork failure
if (pid < 0) {
killflg = 1;
break;
}
// child process
if (pid == 0) {
pid = getpid();
printf("==============n");
#if 0
execlp(cmd, cmd, param, "/", (char *) NULL);
#else
execlp(cmd, cmd, param, (char *) NULL);
#endif
printf("Excec failed; killing the proccess.");
// NOTE/BUG: this is the child so pid is zero, so killing it is wrong
#if 0
kill(pid, SIGKILL);
#else
exit(1);
#endif
}
killflg = 0;
for (;;) {
code = waitpid(pid, &status, WNOHANG);
if (code > 0)
break;
if (killflg)
continue;
secsWaited++;
sleep(1);
if (secsWaited >= waitingTime) {
printf("timeoutn");
kill(pid, SIGKILL);
killflg = 1;
}
}
if (! killflg)
break;
}
#if 0
free(cmd);
free(param);
#endif
if (killflg)
code = EXIT_FAILURE;
else
code = EXIT_SUCCESS;
return code;
}
UPDATE:
Right now, the program will stop after one iteration; if I remove the breakpoint at
if (! killflg)
, it will work as expected. Am I missing something or is this just a misunderstanding?
You are correct--my bad. I had missed the following in your question:
The task is to read a terminal command and to run it every x seconds;
Change the break
into sleep(waitingTime - secsWaited)
.
But, a more robust way to keep track of elapsed time may be via two calls to time(2)
:
After the killflg = 0
, do: time_t todbeg = time(NULL); time_t todelap;
. Then, you can get elapsed time [anywhere] with: todelap = time(NULL) - todbeg;
[here, todelap
is similar to secsWaited
]. This may be better than incrementing secsWaited
.
time
only has seconds resolution. For more precision control, consider using clock_gettime
[has nanosecond resolution].
Here's a function that I use a lot for elapsed time [in fractional seconds]:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
#include <time.h>
double
tvgetf(void)
{
struct timespec ts;
double sec;
clock_gettime(CLOCK_REALTIME,&ts);
sec = ts.tv_nsec;
sec /= 1e9;
sec += ts.tv_sec;
return sec;
}
/*
*
*/
int
main(int argc, char **argv)
{
int waitingTime;
if (argc < 3) {
printf("Invalid number of arguments provided. Please specify a command and exactly one parameter.");
return (EXIT_FAILURE);
}
// -n parameter specified? If so, set the waiting time.
if (argc == 5 && strcmp(argv[3], "-n") == 0) {
waitingTime = atoi(argv[4]);
}
else {
waitingTime = 5; // Default waiting time.
}
char *cmd = argv[1];
char *param = argv[2];
// Print the read command and its param
printf("Command: %s, Parameter: %s, Interval: %dnn", cmd, param, waitingTime);
pid_t pid;
int code = -1;
int status;
int killflg = 1;
double todzero = tvgetf();
for (;;) {
// Declared here for scope
double todbeg = tvgetf();
double todelap;
pid = fork();
// stop on fork failure
if (pid < 0) {
killflg = 1;
break;
}
// child process
if (pid == 0) {
pid = getpid();
printf("============== (%.9f)n",tvgetf() - todzero);
execlp(cmd, cmd, param, (char *) NULL);
printf("Excec failed; killing the proccess.");
exit(1);
}
killflg = 0;
for (;;) {
code = waitpid(pid, &status, WNOHANG);
if (code > 0)
break;
if (killflg)
continue;
usleep(1000);
todelap = tvgetf() - todbeg;
if (todelap >= waitingTime) {
printf("timeoutn");
kill(pid, SIGKILL);
killflg = 1;
}
}
// do _not_ wait -- we already timed out
if (killflg)
continue;
// get final elapsed time for this round and the amount of time
// remaining until the next interval
todelap = tvgetf() - todbeg;
useconds_t time_to_wait = ((double) waitingTime - todelap) * 1e6;
// wait until the next time period
if (time_to_wait > 0)
usleep(time_to_wait);
}
if (killflg)
code = EXIT_FAILURE;
else
code = EXIT_SUCCESS;
return code;
}
Side note: I used usleep
here, but, although slightly more complex, it's considered better to use nanosleep
Your logic was a bit too complicated (e.g. too many different sleep
calls and if/else
ladder logic).
Also, no need to malloc
the argv
strings--they can be used directly.
I've simplified it and restructured a bit to get it to work [please pardon the gratuitous style cleanup]:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
/*
*
*/
int
main(int argc, char **argv)
{
int waitingTime;
if (argc < 3) {
printf("Invalid number of arguments provided. Please specify a command and exactly one parameter.");
return (EXIT_FAILURE);
}
// -n parameter specified? If so, set the waiting time.
if (argc == 5 && strcmp(argv[3], "-n") == 0) {
waitingTime = atoi(argv[4]);
}
else {
waitingTime = 5; // Default waiting time.
}
char *cmd = argv[1];
char *param = argv[2];
// Print the read command and its param
printf("Command: %s, Parameter: %s, Interval: %dnn",
cmd, param, waitingTime);
pid_t pid;
int code = -1;
int status;
int killflg = 1;
for (;;) {
// Declared here for scope
int secsWaited;
secsWaited = 0;
pid = fork();
// stop on fork failure
if (pid < 0) {
killflg = 1;
break;
}
// child process
if (pid == 0) {
pid = getpid();
printf("==============n");
#if 0
execlp(cmd, cmd, param, "/", (char *) NULL);
#else
execlp(cmd, cmd, param, (char *) NULL);
#endif
printf("Excec failed; killing the proccess.");
// NOTE/BUG: this is the child so pid is zero, so killing it is wrong
#if 0
kill(pid, SIGKILL);
#else
exit(1);
#endif
}
killflg = 0;
for (;;) {
code = waitpid(pid, &status, WNOHANG);
if (code > 0)
break;
if (killflg)
continue;
secsWaited++;
sleep(1);
if (secsWaited >= waitingTime) {
printf("timeoutn");
kill(pid, SIGKILL);
killflg = 1;
}
}
if (! killflg)
break;
}
#if 0
free(cmd);
free(param);
#endif
if (killflg)
code = EXIT_FAILURE;
else
code = EXIT_SUCCESS;
return code;
}
UPDATE:
Right now, the program will stop after one iteration; if I remove the breakpoint at
if (! killflg)
, it will work as expected. Am I missing something or is this just a misunderstanding?
You are correct--my bad. I had missed the following in your question:
The task is to read a terminal command and to run it every x seconds;
Change the break
into sleep(waitingTime - secsWaited)
.
But, a more robust way to keep track of elapsed time may be via two calls to time(2)
:
After the killflg = 0
, do: time_t todbeg = time(NULL); time_t todelap;
. Then, you can get elapsed time [anywhere] with: todelap = time(NULL) - todbeg;
[here, todelap
is similar to secsWaited
]. This may be better than incrementing secsWaited
.
time
only has seconds resolution. For more precision control, consider using clock_gettime
[has nanosecond resolution].
Here's a function that I use a lot for elapsed time [in fractional seconds]:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
#include <time.h>
double
tvgetf(void)
{
struct timespec ts;
double sec;
clock_gettime(CLOCK_REALTIME,&ts);
sec = ts.tv_nsec;
sec /= 1e9;
sec += ts.tv_sec;
return sec;
}
/*
*
*/
int
main(int argc, char **argv)
{
int waitingTime;
if (argc < 3) {
printf("Invalid number of arguments provided. Please specify a command and exactly one parameter.");
return (EXIT_FAILURE);
}
// -n parameter specified? If so, set the waiting time.
if (argc == 5 && strcmp(argv[3], "-n") == 0) {
waitingTime = atoi(argv[4]);
}
else {
waitingTime = 5; // Default waiting time.
}
char *cmd = argv[1];
char *param = argv[2];
// Print the read command and its param
printf("Command: %s, Parameter: %s, Interval: %dnn", cmd, param, waitingTime);
pid_t pid;
int code = -1;
int status;
int killflg = 1;
double todzero = tvgetf();
for (;;) {
// Declared here for scope
double todbeg = tvgetf();
double todelap;
pid = fork();
// stop on fork failure
if (pid < 0) {
killflg = 1;
break;
}
// child process
if (pid == 0) {
pid = getpid();
printf("============== (%.9f)n",tvgetf() - todzero);
execlp(cmd, cmd, param, (char *) NULL);
printf("Excec failed; killing the proccess.");
exit(1);
}
killflg = 0;
for (;;) {
code = waitpid(pid, &status, WNOHANG);
if (code > 0)
break;
if (killflg)
continue;
usleep(1000);
todelap = tvgetf() - todbeg;
if (todelap >= waitingTime) {
printf("timeoutn");
kill(pid, SIGKILL);
killflg = 1;
}
}
// do _not_ wait -- we already timed out
if (killflg)
continue;
// get final elapsed time for this round and the amount of time
// remaining until the next interval
todelap = tvgetf() - todbeg;
useconds_t time_to_wait = ((double) waitingTime - todelap) * 1e6;
// wait until the next time period
if (time_to_wait > 0)
usleep(time_to_wait);
}
if (killflg)
code = EXIT_FAILURE;
else
code = EXIT_SUCCESS;
return code;
}
Side note: I used usleep
here, but, although slightly more complex, it's considered better to use nanosleep
edited Nov 21 '18 at 4:10
answered Nov 21 '18 at 0:09
Craig EsteyCraig Estey
14.9k21129
14.9k21129
Okay, that makes sense and helped me understand the related commands. However, I do have one question left: Right now, the program will stop after one iteration; if I remove the breakpoint at "if ( !killflg)", it will work as expected. Am I missing something or is this just a misunderstanding?
– ximilianL
Nov 21 '18 at 0:55
add a comment |
Okay, that makes sense and helped me understand the related commands. However, I do have one question left: Right now, the program will stop after one iteration; if I remove the breakpoint at "if ( !killflg)", it will work as expected. Am I missing something or is this just a misunderstanding?
– ximilianL
Nov 21 '18 at 0:55
Okay, that makes sense and helped me understand the related commands. However, I do have one question left: Right now, the program will stop after one iteration; if I remove the breakpoint at "if ( !killflg)", it will work as expected. Am I missing something or is this just a misunderstanding?
– ximilianL
Nov 21 '18 at 0:55
Okay, that makes sense and helped me understand the related commands. However, I do have one question left: Right now, the program will stop after one iteration; if I remove the breakpoint at "if ( !killflg)", it will work as expected. Am I missing something or is this just a misunderstanding?
– ximilianL
Nov 21 '18 at 0:55
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53403120%2fkilling-a-process-once-time-limit-exceeded%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
any particular reason you're using C for this? Such a task would be much better suited for shell programming or higher level programming languages like python.
– YoYoYonnY
Nov 20 '18 at 23:27
I'm asked to do it in C, it wasn't my idea.
– ximilianL
Nov 20 '18 at 23:34