gpt4 book ai didi

c++ - 编译后 Unix 命令行无法运行程序,没有错误消息

转载 作者:行者123 更新时间:2023-11-28 05:46:14 25 4
gpt4 key购买 nike

我正在尝试运行我从我学校基于 Unix 命令行的服务器编写的 C++ 程序。该程序应该使用 pipe() 和 fork() 之类的命令在子进程中计算一个整数,并通过管道将其发送给父进程。我遇到的问题是,当我在编译后尝试运行该程序时,除了在提示符之前插入一个“0”之外什么都没有发生。我不完全理解 fork 和管道,所以我会发布整个程序以防问题出在我对这些命令的使用上。可能有错误,因为我还没有能够成功运行它。这是我的代码:

#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”的信息。

最佳答案

您的程序完全按照您的指示执行!您将 addRes 送入管道,然后将其打印出来。 addRes 初始化为 0 且从未更改。在您的 child 中,您想传递 num 。此外,您可能还想打印出一个新行 ('\n')。

关于c++ - 编译后 Unix 命令行无法运行程序,没有错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36144307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com