【问题标题】:Creating multiple processes in C在 C 中创建多个进程
【发布时间】:2015-05-24 18:57:22
【问题描述】:

我正在编写一个需要创建多个进程的程序。假设这个数字是 3。我希望这些进程中的每一个都从 1 到 5 进行计数和输出,并在每次计数/输出之间休眠 1 秒。我试图以下列方式做到这一点,但我的 sleep(1) 没有像被打断一样工作。我将不胜感激有关该主题的一些背景知识,我做错了什么以及如何解决此问题。到目前为止,这是我的代码。

/*
 * Creates N > 2 processes.
 */
int main(int argc, const char * argv[])
{
    pid_t pid;

    for(int i = 0; i < N_PROC; i++) {
        pid = fork();
        if(pid == 0) {
            ProcessWork();
            exit(0);
        }
    }
}


/*
 * Work of a single process.
 */
void ProcessWork() {
    char buffer[BUF_SIZE];
    for (int i = 1; i <= 5; i++) {
        sleep(1);
        sprintf(buffer, "PID = %d, count = %d\n", getpid(), i);
        write(1, buffer, strlen(buffer));
    }
}

【问题讨论】:

  • “sleep(1) 不起作用”是什么意思?
  • 您的示例在这里完美运行。你到底有什么问题?
  • 多线程是更好的选择

标签: c process multiprocessing sleep


【解决方案1】:

您的 sleep() 完全可以正常工作。但是,您的问题似乎是父进程不等待子进程终止,因此父进程在子进程执行工作之前终止。因此,它在 Unix 系统上看起来像这样:

% ./a.out
% PID = 41431, count = 1
PID = 41430, count = 1
PID = 41432, count = 1
PID = 41431, count = 2
PID = 41430, count = 2
PID = 41432, count = 2
PID = 41430, count = 3
PID = 41431, count = 3
PID = 41432, count = 3
PID = 41430, count = 4
PID = 41431, count = 4
PID = 41432, count = 4
PID = 41431, count = 5
PID = 41430, count = 5
PID = 41432, count = 5

您应该查看 wait() 系统调用的手册页。您可以在循环中调用该系统调用,只要有孩子,它就会返回终止孩子的 pid,一旦孩子用完,它就会返回 -1 和 errno == ECHILD。该 ECHILD 可用作循环终止标准。

【讨论】:

    【解决方案2】:

    如果我理解您的问题,请等待分叉进程终止...

    int main(int argc, const char * argv[])
    {
        pid_t pid[N_PROC];
    
        for(int i = 0; i < N_PROC; i++) {
            pid_t cur_pid = fork();
            if(cur_pid == 0) {
                pid[i] = cur_pid;
                ProcessWork();
                exit(0);
            }
        }
    
        for(int i = 0; i < N_PROC; i++)
            wait(&pid[i]);
    }
    

    【讨论】:

    • 我认为你有一个轻微的逻辑错误:看起来你所有的 cur_pid[i] 值都将设置为 0?
    猜你喜欢
    • 2014-05-11
    • 2021-12-12
    • 1970-01-01
    • 2015-12-23
    • 1970-01-01
    • 2013-03-20
    • 1970-01-01
    • 2022-10-02
    • 1970-01-01
    相关资源
    最近更新 更多