Reputation:
I wrote this basics forking program in C language. But the compiler issues me error. The code is
#include<stdio.h>
#include<sys/stat.h>
#include<ctype.h>
void childProcess(){
printf("From child process with process id %d\n", getpid());
}
void parentProcess(){
printf("Parent Process with id %d\n", getpid());
pid_t pid = fork();
if (pid == 0){
childProcess();
} else if (pid > 0){
printf("Parent spawned process %d\n", pid);
} else{
printf("Forking isn't supported!\n");
}
}
int main(){
parentProcess();
}
The error is
C:\Users\ADMINI~1\AppData\Local\Temp\ccORJc6N.o forking.c:(.text+0x3e): undefined reference to `fork'
Upvotes: 1
Views: 328
Reputation: 15642
To unify the best answers I see so far (which aren't necessarily the most popular):
fork
manual, you're missing the <unistd.h>
header include (and <sys/types>
, depending on the POSIX standard you use). Note that this is an error in the program when a POSIX-compliant OS is targeted, which brings me to the next point:fork
, of course... and Windows is not one of them. Note that this isn't an error in the program; it's an error in the selection of the OS.I found another error in the program. %d
tells printf
to print an argument of type int
, but the actual type you've provided is pid_t
. According to the printf
manual (which I highly recommend reading and fully understanding multiple times for the purpose of writing better code; you'll learn a lot), "If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined." You need an explicit conversion. For example:
printf("From child process with process id %d\n", (int) getpid());
printf("Parent Process with id %d\n", (int) getpid());
printf("Parent spawned process %d\n", (int) pid);
The conversion to int
is itself an error; according to the <sys/types.h>
header manual, a POSIX-compliant implementation "shall support one or more programming environments in which the widths of blksize_t
, pid_t
, size_t
, ssize_t
, suseconds_t
, and useconds_t
are no greater than the width of type long
." In such an environment, a conversion to long
and using the corresponding %ld
(that's an ell, by the way) directive would be more appropriate:
printf("From child process with process id %ld\n", (long) getpid());
printf("Parent Process with id %ld\n", (long) getpid());
printf("Parent spawned process %ld\n", (long) pid);
Upvotes: 1
Reputation: 309
You are using Windows, looks like you can't do that on Windows. Here are some related posts:
These were the first three links when googling your error: undefined reference to `fork'
Upvotes: 2
Reputation: 1069
You're missing a library:
Add this to the top of your code
#include <sys/types.h>
Upvotes: 1