c - C 中的退出过程值

标签 c unix signals fork

在这段代码中我接收到一些命令,将它们转换成一个数组并在一个进程中执行它们。

我的问题是,我怎样才能让一个进程超过 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]);
    }

最佳答案

您可以:

  1. 捕获 SIGCHLD 以捕获子进程终止并通过调用 wait 移除僵尸进程,如果所有进程终止则移除超时
  2. 设置超时警报并捕获SIGALRM杀死剩余进程并等待移除僵尸
  3. sigsuspendpause 您的进程使其等待其中的一些事件

关于c - C 中的退出过程值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34499962/

相关文章:

kernel - 在执行期间访问 .eh_frame 数据

linux - 更智能、更简洁的方法来匹配 shell 脚本中的输入变量?

python-2.7 - 将Python日期转换为Unix时间戳

linux - gawk 命令在服务器上运行时给出空白输出

perl - 在 Perl 中忽略信号和告诉它什么都不做有什么区别?

c - 将参数传递给 C 中的信号处理程序

c - 我正在尝试用 c 计算指数,但这就是得到的

c - 不使用字符串的可变长度算术计算器?

c - UNIX/Linux 信号处理 : SIGEV_THREAD

cmake找不到头文件