在这段代码中我接收到一些命令,将它们转换成一个数组并在一个进程中执行它们。
我的问题是,我怎样才能让一个进程超过 exec_timeout 秒才能终止?
有什么帮助吗?
void exec_Task(int exec_timeout, char *args, int n){
signal(SIGALRM, handler);
int i=0;
int j=0;
int len;
int pa;
int flag;
pid_t p;
int fd[2];
const char s[2] = "|"; //sets the delimiter for the token
char *token;
char tasks[n][50];
wordexp_t wt; //warning cleaner
char **w; //wordexp related
token = strtok(args, s); // breaks the string into smaller strings whenever the char '|' appears
//token gets the value of the first substring
i =0;
while( token != NULL ) // walk through other tokens
{
strcpy(tasks[i],token); // inserts them in an 2D array
i++;
token = strtok(NULL, s);
}
for(i=0; i<(sizeof(tasks[0])-2); i++) //cleans the first task since it has the command char appanded
tasks[0][i]=tasks[0][i+2];
for(i=0;i<n ;i++){ //Number of commands to execute
pipe(fd);
p=fork(); //Creates child process
wordexp(tasks[i], &wt, 0);
w = wt.we_wordv;
if(p==0){
if(i<n-1){
close(fd[0]);
dup2(fd[1],1);
}
dup2(pa,0);
//executes command
if(execvp(w[0],w)== -1){
perror("execvp error");
}
_exit(1);
}
else{
close(fd[1]);
pa=fd[0];
}
}
for(i=0; i<n ;i ++){
int status=0, f=0;
printf("wifexited: %d\n",WIFEXITED(status));
wait(&status);
alarm(3);
pause();
kill(p,SIGKILL);
}
close(fd[1]);
}
最佳答案
您可以:
- 捕获
SIGCHLD
以捕获子进程终止并通过调用wait
移除僵尸进程,如果所有进程终止则移除超时 - 设置超时警报并捕获
SIGALRM
以杀死
剩余进程并等待
移除僵尸 sigsuspend
或pause
您的进程使其等待其中的一些事件
关于c - C 中的退出过程值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34499962/