【发布时间】:2016-07-08 17:52:54
【问题描述】:
我正在尝试从我学校的基于 Unix 命令行的服务器上运行我一直在编写的 C++ 程序。该程序应该使用诸如 pipe() 和 fork() 之类的命令来计算子进程中的整数并通过管道将其发送给父进程。我遇到的问题是,当我在编译后尝试运行程序时,除了在提示符之前插入“0”之外,什么都没有发生。我不完全理解分叉和管道,所以我会发布整个程序,以防问题出在我使用这些命令的情况下。可能有错误,因为我还没有成功运行它。这是我的代码:
#include <cstdlib>
#include <iostream>
#include <string>
#include <array>
#include <cmath>
#include <unistd.h>
using namespace std;
// Return bool for whether an int is prime or not
bool primeChecker(int num)
{
bool prime = true;
for (int i = 2; i <= num / 2; ++i)
{
if (num%i == 0)
{
prime = false;
break;
}
}
return prime;
}
int main(int argc, char *argv[])
{
int *array;
array = new int[argc - 1]; // dynamically allocated array (size is number of parameters)
int fd[2];
int count = 0; // counts number of primes already found
int num = 1; // sent to primeChecker
int k = 1; // index for argv
int addRes = 0;
// Creates a pair of file descriptors (int that represents a file), pointing to a pipe inode,
// and places them in the array pointed to. fd[0] is for reading, fd[1] is for writing
pipe(fd);
while (k < argc)
{
if (primeChecker(num)) // if the current number is prime,
{
count++; // increment the prime number count
if (count == (stoi(argv[k]))) // if the count reaches one of the arguments...
{
array[k - 1] = num; // store prime number
k++; // increment the array of arguments
}
}
num++;
}
pid_t pid;
pid = fork();
if (pid < 0) // Error occurred
{
cout << "Fork failed.";
return 0;
}
else if(pid == 0) // Child process
{
for (int i = 0; i < (argc-1); i++)
{
// Close read descriptor (not used)
close(fd[0]);
// Write data
write(fd[1], &addRes, sizeof(addRes)); /* write(fd, writebuffer, max write lvl) */
// Close write descriptor
close(fd[1]);
}
}
else // Parent process
{
// Wait for child to finish
wait(0);
// Close write descriptor (not used)
close(fd[1]);
// Read data
read(fd[0], &addRes, sizeof(addRes));
cout << addRes;
// Close read descriptor
close(fd[0]);
}
return 0;
}
这是我在尝试编译和运行程序时在命令窗口(包括提示符)中看到的内容:
~/cs3270j/Prog2$ g++ -o prog2.exe prog2.cpp
~/cs3270j/Prog2$ ./prog2.exe
0~/cs3270j/Prog2$
然后什么也没有发生。我尝试了不同的命名变体以及从“a.out”运行它但没有成功。
tl;dr 在编译并尝试执行我的程序后,Unix 命令提示符只是在提示符的开头添加一个 0 并且不执行任何其他操作。
任何人都可以给我的任何帮助将不胜感激,因为我找不到任何关于出现在提示之前的“0”的信息。
【问题讨论】:
-
0出现在提示符前面是您的代码在没有换行符的情况下打印出0的结果。cout << addRes << endl应该可以解决这部分问题。 -
您是否尝试在调试器中运行您的程序并逐步查看会发生什么?你发现了什么?
标签: c++ unix command fork putty