Error running this fork code in my eclipse, and also have some concept confusion around this code

352 views Asked by At

So this a simple C code on Fork that my professor gave us, I'm trying to get the output for this code, but when I tried to run in eclipse I get the following error:

Info: Internal Builder is used for build
gcc -O0 -g3 -Wall -c -fmessage-length=0 -o ForkDemo1.o "..\\ForkDemo1.c" 
..\ForkDemo1.c: In function 'main':
..\ForkDemo1.c:18:1: warning: implicit declaration of function 'fork' [-Wimplicit-function-declaration]
 if( (pid = fork()) = -1) {
 ^
..\ForkDemo1.c:18:20: error: lvalue required as left operand of assignment
 if( (pid = fork()) = -1) {

But my basic confusion around this code is: what is pid_t pid's value? is it 11 or 10, is it creating a child from parent?

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>


int global = 10;

int main(int argc, char* argv[]) {

int local = 0;
pid_t pid;


printf("Parent process: (Before fork())");
printf(" local = %d, global = %d \n", local, global);


if( (pid = fork()) = -1) {
perror("fork");
exit(1);
}
else if (0 == pid) {

/* child executes this branch */
printf("After the fork in the child:");
local++;
global++;
printf("local = %d, global  = %d\n", local, global);
} else {
/* parent execute this branch */

sleep(2); /* sleep long enough for child's output to appear */
}

/* both process excute this print statement */
printf("pid = %d. local = %d, global = %d\n", getpid(), local, global);

return 0;
}
1

There are 1 answers

2
Eugene Sh. On

Change this:

if( (pid = fork()) = -1) {

to this:

if( (pid = fork()) == -1) {

As for the warning about implicit declaration of fork, it might happen if you work in Windows OS and using a gcc toolchain for MinGW, which is providing unistd.h but not implementing fork. In such a case you should switch to another environment. Ideally - Linux, but you can also use gcc for Cygwin, which is providing fork