热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

在C中使用管道运行并发进程-RunningconcurrentprocessesusingpipeinC

ImworkingonanassignmentinCaimedatusingapipetopassvariablesbetweentwoprocesses.Bot

I'm working on an assignment in C aimed at using a pipe to pass variables between two processes. Both processes must be forked from the parent, and they must run concurrently to pass one character at a time (sort of demonstrated below).

我正在研究C中的一项任务,旨在使用管道在两个进程之间传递变量。这两个进程必须从父进程分叉,并且它们必须同时运行以一次传递一个字符(如下所示)。

The issue I'm having is that the fork()ed processes are not running concurrently. The sender seems to go first, and after running for ~26 seconds the receiver begins. Here is the code I have written:

我遇到的问题是fork()ed进程没有并发运行。发送者似乎先行,并且在运行约26秒后接收器开始。这是我写的代码:

#include 

int ret;
int pipearray[2];
char buffer[26];

void mysender();
void myreceiver();

int main()
{
  int pid = 0;
  int i = 0;
  ret = pipe(pipearray);


  while (i <2) {
    pid = fork();
    if ( pid == 0 && i == 0 ) /* child process execution (receiver) */
      {
    myreceiver();
    printf("Your receiver is done\n");
    exit(0);
      }

     else if ( pid == 0 && i == 1 ) /* now executes sender */
     {
    mysender();
    printf("Your sender is done\n");
    exit(0);
     }
    ++i;
  }

  close(pipearray[0]);
  close(pipearray[1]);
  sleep(30);
  printf("Parent function has finished.\n");      

  return 0;
}

void mysender() 
{
  char c;
  int index = 90;
  close(pipearray[0]);

  while (index > 64) /* loop for all values of A-Z in ASCII */ 
    {      
      c = (char) index;
      open(pipearray[1]);
      write(pipearray[1], c, sizeof(c)); /* Sends letter to pipe */
      --index;
      sleep(1);
    }

  close(pipearray[1]);
}

void myreceiver()
{
  int index = 0;
  close(pipearray[1]);

  while(buffer != 'A') /*loop runs until 'A' is handled */
  { 
    sleep(1);
    open(pipearray[0]);
    read(pipearray[0], buffer, 1);
    printf("%s", &buffer);
    index++;
    if ( index == 26 ) { break; }
  }

  close(pipearray[0]);
}

Expected Result:

预期结果:

ZYXWVUTSRQPONMLKJIHGFEDCBA
Your sender is done
Your receiver is done
The parent function has finished.

My result:

我的结果:

Your sender is done
The parent function has finished.
Your receiver is done

I'm very new to C programming but I've been banging away at this for a while. Any tips to why these might not be running simultaneously would be very appreciated.

我对C编程很陌生,但我已经暂时搁置了一段时间。任何关于为什么这些可能不会同时运行的提示将非常感激。

1 个解决方案

#1


2  

There is many errors in your code. Don't try to open the pipe after fork, it is already open and has no name. Write should use the address of c. Read must read into the right place. A flush must be done after write to stdout. Your conditional must be slightly modified to be guaranteed correct. The parent process must wait its children. Here is the modified code :

您的代码中存在许多错误。不要尝试在fork之后打开管道,它已经打开并且没有名称。写应该使用c的地址。阅读必须读到正确的地方。写入stdout后必须刷新。您的条件必须稍加修改才能保证正确。父进程必须等待其子进程。这是修改后的代码:

#include 
#include 
#include 
#include 
int ret;
int pipearray[2];
char buffer[26];

void mysender();
void myreceiver();

int main()
{
  int pid = 0;
  int i = 0;
  ret = pipe(pipearray);


  while (i <2) {
    pid = fork();
    if ( pid == 0 && i == 0 ) /* child process execution (receiver) */
      {
        myreceiver();
        printf("Your receiver is done\n");
        exit(0);
      }

    else if ( pid == 0 && i == 1 ) /* now executes sender */
      {
        mysender();
        printf("Your sender is done\n");
        exit(0);
      }
    ++i;
  }

  close(pipearray[0]);
  close(pipearray[1]);
  // Don't sleep, but wait until the end of the two children
  wait(NULL);
  wait(NULL);
  //  sleep(30);
  printf("Parent function has finished.\n");      

  return 0;
}

void mysender() 
{
  char c;
  int index = 90;
  close(pipearray[0]);

  while (index > 64) /* loop for all values of A-Z in ASCII */ 
    {      
      c = (char) index;
      // try to open a anonymous pipe is a non-sense
      //      open(pipearray[1]);
      // Send a buffer by its address
      write(pipearray[1], &c, sizeof(c)); /* Sends letter to pipe */
      --index;
      sleep(1);
    }

  close(pipearray[1]);
}

void myreceiver()
{
  int index = 0;
  close(pipearray[1]);

  // Ensure condition is entered first
  buffer[index] = 0;
  // This is not the best condition ever, but ok.
  while(buffer[index] != 'A') /*loop runs until 'A' is handled */
  { 
    sleep(1);
    // Don't open an anonymous pipe
    //    open(pipearray[0]);
    // Read at the right position
    read(pipearray[0], buffer+index, 1);
    // print and flush, could also be printf("%s"...); flush(stdout);
    printf("%s\n", buffer);
    index++;
    if ( index == 26 ) { break; }
  }

  close(pipearray[0]);
}

Now, consider to remove the sleeps in the reader, as it will be synchronized with the writes such that no read is possible if no write has been done. Alos consider to read more that one byte, because there is no concept of message, so that you can read as much byte you consider necessary to read, and as usual it is better to try reading a bunch of bytes when you can.

现在,考虑删除读取器中的睡眠,因为它将与写入同步,以便在没有写入的情况下无法读取。 Alos考虑读取更多的一个字节,因为没有消息的概念,因此您可以读取您认为需要读取的字节数,并且通常最好尽可能尝试读取一堆字节。


推荐阅读
author-avatar
码天下
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有