流程环

时间:2013-11-18 21:54:41

标签: c process

我正在尽我所能在C中创建一个流程环,从而发送一个简单的消息。我写了以下代码:

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

#define BUF_SIZE 1024

char message[40];
char buf [BUF_SIZE];
int last_pipe_dsc[2];

void create_process(int n, int dsc_to_close){

  if (n>0){
    int pipe_dsc[2];

    pipe (pipe_dsc);

    switch (fork()) {

      case 0:
        close(pipe_dsc[1]);
        if (dsc_to_close!=-1) {
          close(dsc_to_close);
        }
        read (pipe_dsc[0], buf, BUF_SIZE - 1);
        printf ("Message received by process %d: %s\n", getpid(), buf);
        create_process(n-1, pipe_dsc[0]);
        exit(0);

      default:
        close (pipe_dsc[0]);
        sprintf(message, "'Hello world! I am process %d!'", getpid());
        write (pipe_dsc[1], message, sizeof(message));
        printf ("Message sent by process %d: %s\n", getpid(), message);
        wait(0);
        if (dsc_to_close != -1) exit(0); 
    }
  }else{

    pipe(last_pipe_dsc);
    sprintf(message, "'Hello world! I am process %d!'", getpid());
    write (last_pipe_dsc[1], message, sizeof(message));
    printf ("Message sent by process %d: %s\n", getpid(), message);

    exit(0);
  }
}

int main(int argc, char *argv[])
{

  create_process(atoi(argv[1]), -1);
  read (last_pipe_dsc[0], buf, BUF_SIZE - 1);
  printf ("Message received: %s\n", buf);

  return 0;
}

但是,它不能正常工作。我发现描述符last_pipe_dsc [0]和last_pipe_dsc [1]出了问题。 整个程序在main()结束时执行read()函数失败。 我不知道出了什么问题。请帮忙。 提前谢谢!

0 个答案:

没有答案