View Full Version : C code in operating systems with fork() system call. What does this code do?

03-21-2013, 05:39 AM
For OS class we have been given a code that we have to explain. It mostly has to do with creating new processses using the fork() system call and getting their respective IDs. The teacher gave us about 6 sets of code to analyze and explain, i have done three. However, this specific one is giving me trouble, I fail to understand what is going on. We are using FreeBSD on a virtual machine to write and compile the code with gcc and then run int with ./a.out. here is the code

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

int main (int argc, char *argv[]) {
pid_t childpid = 0;
int i, n;

if (argc != 2){ /* check for valid number of command-line arguments */
fprintf(stderr, "Usage: %s processes\n", argv[0]);
return 1;
n = atoi(argv[1]);
for (i = 1; i < n; i++)
if (childpid = fork())

fprintf(stderr, "i:%d process ID:%ld parent ID:%ld child ID:%ld\n",
i, (long)getpid(), (long)getppid(), (long)childpid);
return 0;

can someone specifically explain to me also what happens in the n = atoi(argv[]) statement?
and also what happens in the for loop where it breaks if (childpid == 0). Also about the meaning of the argc and argv[] please

this is the first time we are doing this kind of problems. I am also not very familiar with C, having been previously coding on the similar but not identical C++.

Thanks for any help!