Search code examples
coutputforkatoi

correct output for this fork concept in C


So for some reason I can't get the output of this code in C, so I can only ask a few conceptual question on this code below:

  1. What does int N = atoi(argv[i]); do? is it just define integer N as an array?
  2. In the for loop, what does if (-1 = fork()) mean? Is -1 means its an error or not the right loop? That means I can't create a child using fork?
  3. What does the getpid() do in the call to the printf function?
  4. And what should the right output be?

code:

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


int main (int argc, char* argv[] ) {
    int i;
    int N = atoi(argv[i]);
    printf("Create processes....\n");
    for (i = 0; i < N; i++) {
        if (-1 = fork())
            exit(1);
    }
    printf("Process id  = %d\n", getpid());
    fflush(stdout);
    sleep(1);
    return 0;
}

Solution

  • Many of the questions you have asked can be answered by just looking into the man pages. Anyway I will try to explain them.

    1) int atoi(const char *str) str -- This is the string representation of an integral number. This function atoi returns the converted integral number as an int value. If no valid conversion could be performed, it returns zero.

    As for your code, i has garbage value stored in it. So the value of atoi(argv[i]))is unpredictable. you might want to assign a value for i.

    2) -1 == fork() , (I assume you have made a syntax error in your code, and you have figured that out already) what happens there is we check the return value of the fork() function, If check the manual, fork() is used to create a new process. If it failed to create a new process then it return -1. It would make much sense if it is written like fork() == -1

    3) getpid() returns the process ID of the calling process. (This is often used by routines that generate unique temporary filenames.)

    4) What do you mean by right output? have you tried run the code and got any errors? please elaborate

    If you run the corrected code with a command line argument, this is what the output looks like.

    de@ubuntu:~/Desktop$ ./a.out 2
    Create processes....
    Process id  = 25405
    Process id  = 25406
    Process id  = 25408
    Process id  = 25407