Search code examples
clinuxprocessforkcompiler-flags

Creating Processes in Linux using fork() Function


I've been trying to compile a piece of C code which should create processes using the fork() function.`

#include <stdio.h>
#include <unistd.h>
main()
{
    int n=15, z=20, count=3, mult=1;
    while(count<3)
    {
        if(z!=0)
        {
            z=fork();
            n=n+15;
        }
        else
        {
            z=fork(); n=n+10; mult=mult*n;
        }
        printf(" z=%d   mult=%d",z,mult);
        count=count+1;
    }
}

Compiled with "gcc -Wall -W -Werror main.c -o ProcessCreateC" in the terminal. I'm getting error:

main.c:3:5: error: return type defaults to ‘int’ [-Werror=return-type]
main.c: In function ‘main’:
main.c:20:5: error: control reaches end of non-void function [-Werror=return-type]
cc1: all warnings being treated as errors

Since I only have experience compiling in Windows and have little experience with Linux, I have no idea what is causing this. Any ideas??


Solution

  • Add return 0;or a similar expression that returns an integer, to the end of your main(), and change main() to int main(), and I think you will find that the code works fine.

    When no return type is specified for main(), it defaults to int. Furthermore, with the compiler flags you have enabled, not specifying a type for main() causes an error.