【发布时间】:2015-04-09 01:56:43
【问题描述】:
这个程序模拟了 Dijkstra 的生产者/消费者问题的一个变体。首先创建一个管道,然后使用 fork() 创建一个子进程。然后,孩子将向管道写入一个粗略完成随机生成的“股市行情信息”。等待子/生产者进程写入此信息后,父/消费者进程将其读出。
第一个输出是正确的:
Produced: FPOO 57.83 +0.43
Consumed: FPOO 57.83 +0.43
然而,在此之后的任何输出都会显示“Consumed: info from first read”:
Produced: RJII 71.30 -2.71
Consumed: FPOO 57.83 +0.43
我不确定为什么会发生这种情况,因为我的 tickerInfo 正在改变。这就是为什么我怀疑我错误地读取了管道,或者我的分叉进程的结构不正确。
我已经用 g++ 编译了代码。它需要一个参数作为您希望程序运行的秒数。
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
// generate info for each stock entry
void generateTickerInfo(char * info) {
int i;
int randNum = 0;
srand(time(NULL)); // generate seed for random
// generate 4 characters for STOCK sym
for(i = 0; i < 4; i++) {
randNum = rand() % 26 + 65;
info[i] = (char)(randNum);
}
info[4] = ' ';
// generate price traded
for(i = 5; i < 7; i++) {
randNum = rand() % 8 + 1;
info[i] = '0' + randNum;
}
info[7] = '.';
for(i = 8; i < 10; i++) {
randNum = rand() % 9;
info[i] = '0' + randNum;
}
info[10] = ' ';
// determine if + or - for change amount
randNum = rand();
if(randNum % 2 == 1) {
info[11] = '+';
}
else {
info[11] = '-';
}
// generate change amount
randNum = rand() % 9;
info[12] = '0' + randNum;
info[13] = '.';
for(i = 14; i < 16; i++) {
randNum = rand() % 9;
info[i] = '0' + randNum;
}
}
// ** constant and global variables **
const int BUFFER_SIZE = 25;
// ** main code **
int main(int argc, char *argv[]) {
pid_t cpid; // child process id
int myPipe[2]; // [0] read, [1] write
char * tickerInfo; // hold current tickerInfo
tickerInfo = new char[BUFFER_SIZE]; // info passed through pipe
char buf[BUFFER_SIZE];
time_t currentTime, stopTime;
// initialize time variables
if(argc < 2) {
printf("Invalid arg. Type as 'foo.out (# seconds)'");
exit(0);
}
else {
currentTime = time(NULL);
stopTime = time(NULL) + (time_t)atoi(argv[1]);
}
int pipeReturn = pipe(myPipe);
if(pipeReturn == -1) { // handle pipe creation error
perror("pipe error...");
exit(0);
}
// main loop; continue until desired time has elapsed
while(currentTime < stopTime) {
cpid = fork();
if(cpid < 0) { // handle process creation error
perror("forking error...\n");
exit(0);
}
else if(cpid == 0) { // child process
close(myPipe[0]); // child does not need to read
generateTickerInfo(tickerInfo);
write(myPipe[1], tickerInfo, BUFFER_SIZE);
printf("Produced: %s\n", tickerInfo);
exit(0);
}
else if(cpid > 0) { // parent process
wait(0);
close(myPipe[1]); // parent does not need to write
read(myPipe[0], buf, BUFFER_SIZE);
printf("Consumed: %s\n", buf);
}
sleep(1);
currentTime = time(NULL);
}
return 0;
}
【问题讨论】:
-
查看
read()的返回值。它可能无法读取任何内容,因此它打印存储在buf上的当前值。良好的编程习惯总是将缓冲区初始化为空字符串。此外,父进程永远不会重新打开管道,因此,成功 close(myPipe[1]) 什么都不做。
标签: c linux pipe fork inter-process-communicat