【问题标题】:Get return status without freezing until childs return在孩子返回之前获得返回状态而不冻结
【发布时间】:2014-06-25 13:16:42
【问题描述】:

我需要完全按照定义的时间间隔运行子进程。 exec() 之后的 wait() 搞砸了时间。如何在不冻结执行/弄乱时间的情况下从孩子那里获得返回值?如果这不可能或非常困难,那么我怎样才能在不留下僵尸的情况下丢弃返回值?

示例代码: (目标是以 10 秒的间隔运行所有作业 [])

#include<stdio.h>
#include<string.h>
#include<time.h>
#include<unistd.h>
#include<sys/types.h>
main() {
        int i, status;
        char jobs[3][100+1];
        time_t t;
        pid_t pid;
        strncpy(jobs[0], "sleep 3", 100);
        strncpy(jobs[1], "sleep 5", 100);
        strncpy(jobs[2], "sleep 10", 100);
        while (1) {
                t = time(NULL);
                sleep(5 - t % 5);
                printf("executing jobs. time: %s", ctime(&t));
                for (i = 0; i < 3; i++) {
                        t = time(NULL);
                        pid = fork();
                        if (pid == 0) {
                                printf("run: %s, pid %d, time: %s\n", jobs[i], (int) getpid(), ctime(&t));
                                execl("/bin/sh", "/bin/sh", "-c", jobs[i], (char *) NULL);
                        }
                }
                while ((pid = wait(&status)) > 0) {
                        t = time(NULL);
                        printf("job complete. pid: %d, return: %d, time: %s\n", (int) pid, status, ctime(&t));
                }
                t = time(NULL);
                printf("done. time: %s", ctime(&t));
                sleep(10);
        }
}

【问题讨论】:

    标签: c exec fork posix wait


    【解决方案1】:

    您可以改用waitpid 函数和WNOHANG 标志。

    【讨论】:

    • 谢谢。 waitpid(-1, &status, WNOHANG | WUNTRACED) 解决了这个问题。
    【解决方案2】:

    您可以将waitpid (here) 与WNOHANG 和可能的WUNTRACED 选项一起使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-16
      • 1970-01-01
      • 1970-01-01
      • 2011-03-03
      • 1970-01-01
      • 1970-01-01
      • 2014-03-31
      • 2018-02-27
      相关资源
      最近更新 更多