gpt4 book ai didi

c - 获取声明错误

转载 作者:行者123 更新时间:2023-11-30 17:00:54 25 4
gpt4 key购买 nike

我正在尝试用 C++ 运行以下代码。我收到了一些我似乎无法弄清楚的声明错误。错误 block 在代码下方给出。

我正在尝试编写一个程序,使用 fork() 系统调用来计算子进程中给定数字的阶乘。输入的整数将通过命令行给出。对于前。如果给定 6,则输出将为 720。由于父级和子级都有自己的数据副本,因此子级必须输出阶乘。父进程必须调用 wait() 来等待子进程完成才能退出程序。

#include<stdio.h>
#include<sys/wait.h>
#include<stdlib.h>

int main( ){
int num;
int fact=1;
int pid, k=1;
int status;
printf("Enter a number....nn");
scanf("%d",&num);
printf("n");
pid = fork();
if (pid == -1){
printf("Error Occured in Forking a Process..n");
exit(0);
}
//child process
if (pid==0){
printf("nnChild PID is %ldnn", (long) getpid());
int i=0;
if(num==0||num==1){
fact=1;
exit(fact);
}
else{
for(i=1;i<=num;i++){
fact = fact * i;
//printf("fact= %d",fact);
}
printf("n Child Execution Completed...n");
exit(fact);
}
}
else{
wait(&k);
printf(" K= %d",k);
int f=WEXITSTATUS(k);
printf("nNow in parentnn");
printf("nn Factorial of %d is %d ",num,f);
}
}

尽管代码中声明了 fork,但我收到这些错误:

main.cpp:13:13:错误:“fork”未在此范围内声明
pid = fork();
main.cpp:20:48: 错误:'getpid' 未在此范围内声明 printf("nnChild PID is %ldnn", (long) getpid());

最佳答案

fork()getpid() 的定义未知,因为您没有包含正确的头文件:

#include <unistd.h>
#include <sys/types.h>

要了解这些系统功能必须包含哪些内容,可以引用 man 第 2 部分。例如:man 2 fork

关于c - 获取声明错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37326439/

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