Reputation: 57
I am trying to run the following piece of code in C++. I am getting a couple of declaration errors that I can't seem to figure out. The errors block is given below the code.
I'm trying to write a program that computes the factorial of a given number in the child process, using the fork() system call. The input integer will be given through the command line. For ex. if 6 is given, output will be 720. Since the parent and child have their own copies of the data, the child will have to output the factorial. The parent has to invoke the wait () call to wait for the child process to complete before exiting the program.
#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);
}
}
I'm getting these errors, although fork is declared in the code:
main.cpp:13:13: error: 'fork' was not declared in this scope
pid = fork();
main.cpp:20:48: error: 'getpid' was not declared in this scope printf("nnChild PID is %ldnn", (long) getpid());
Upvotes: 0
Views: 647
Reputation: 1174
The definition of fork()
and getpid()
are not knwon because you didn't include the right header files :
#include <unistd.h>
#include <sys/types.h>
To know what you have to include for those system function, you can refer to the man section 2. For example : man 2 fork
Upvotes: 0
Reputation: 507
Try using
#include <unistd.h>
#include <sys/types.h>
These are the header files where the functions and necessary types are declared.
Upvotes: 0