【发布时间】:2015-10-27 05:55:23
【问题描述】:
我正在使用 C 语言进行赋值,旨在使用管道在两个进程之间传递变量。两个进程都必须从父进程派生,并且它们必须同时运行才能一次传递一个字符(如下所示)。
我遇到的问题是 fork()ed 进程没有同时运行。发送者似乎先走,运行约 26 秒后接收者开始。这是我写的代码:
#include <stdio.h>
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]);
}
预期结果:
ZYXWVUTSRQPONMLKJIHGFEDCBA
Your sender is done
Your receiver is done
The parent function has finished.
我的结果:
Your sender is done
The parent function has finished.
Your receiver is done
我对 C 编程非常陌生,但我已经为此努力了一段时间。任何关于为什么这些可能不会同时运行的提示将不胜感激。
【问题讨论】:
-
open(pipearray[1])到底应该做什么? -
Protip:总是用
-Wall -Wextra -Werror编译。