【问题标题】:fork () in C: Counting from 1 to 1000C中的fork():从1数到1000
【发布时间】:2021-04-17 18:41:56
【问题描述】:

我认为我很接近,但这里缺少一些细节。

任务: 用 C 语言编写一个程序,创建父进程和子进程。父亲和孩子都在“使用”循环从 1 数到 1000。 父进程只统计偶数,子进程只统计奇数。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>


void main (){

int id = fork();
int i;

if (id == 0){

    for (i=1;i<=1000;i=i+2){
    printf("%d\n",i);
    }
}

if (id >  0){

    for (i=0;i<=1000;i=i+2){
    printf("%d\n",i);
    wait(0);
    }
  }
}

我在这里遇到的问题是,所有数字都完全混淆了。 看来我的等待系统调用无法正常工作:( 我很感激任何帮助。在此先感谢:)

【问题讨论】:

  • main() 应该是 int,而不是 void
  • 阅读wait()的文档;它不像你想象的那样做。假设您想要按顺序查看所有数字,您需要在两个进程之间进行某种形式的同步,例如信号量。要正确获得它,需要做很多工作;恐怕你还没有完全“接近”。
  • 这不应该把它们都混为一谈。它要么首先是所有奇数,要么是 0 到 2 之间的所有奇数。
  • 您是否希望按顺序打印数字?任务中没有任何内容表明这是一项要求。
  • 是的,这就是我所期待的。所以我需要一个信号量吗?

标签: c process fork


【解决方案1】:
Your wait system call should placed out of for loop, because there's only one child process to wait.
like that 

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <sys/wait.h>
    
    
    void main (){
    
    int id = fork();
    int i;
    
    if (id == 0){
    
        for (i=1;i<=1000;i=i+2){
        printf("%d\n",i);
        }
    }
    
    if (id >  0){
    
        for (i=0;i<=1000;i=i+2){
        printf("%d\n",i);
       
        }
        wait(0);
      }
    }

【讨论】:

  • 这并不能解决问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-31
  • 1970-01-01
  • 2018-06-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多