I have a doubt in the following piece of code and its behaviour:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define N 5
#define nt 1
int pm[N][2],pid[N];
int i,j,size;
char s[100];
int count=0;
int main()
{
for(i=1;i<N;i++)
{
printf("\n i=%d",i);
if(pid[i]=fork() == -1)
{
printf("\n fork not wrking");
exit(1);
}
else if(pid[i]>0)
{
printf(" \n pid:%3d\n",pid[i]);
break;
}
}
return 0;
}
I initially thought that the code will spawn a process and skip out of the loop.
Thereby,
1 spawns 2 and skips out.
2 spawns 3 and skips out
3 spawns 4 and skips out
4 spawns 5 and skips out.
I tried executing this code and was surprised by the answer i got ( for the printf of i in the code). Here is the output
i=1
i=2
i=3
i=2
i=4
i=3
i=3
i=3
i=4
i=4
i=4
i=4
i=4
i=4
i=4
Can Anyone please explain to me what is going on here.
NOTE: I am working on a Solaris machine.
Update
You’re missing a set of parentheses in your updated code. That should be
if ((pid[i] = fork()) == -1)notif (pid[i] = fork() == -1)!The latter is equivalent to
if (pid[i] = (fork() == -1))due to precedence rules. It ends up assigning 0 topid[i]each time through the loop, so the parents think they are child processes and don’t break out of the loop.I agree with your analysis of what should happen. The parent should spawn a child and then quit, so each
i=nprintout should only show up once.Are you sure you typed it in exactly as specified in your question? I ran your program (with minor modifications) and got the output you predicted:
Note that I moved the
\nin the printout to the end. When you put it at the beginning of the line you end up withstdoutnot being flushed, so you get multiple printouts when the parent and child processes both flush their output buffers. That might be the cause of your problem. FWIW on my Mac I got each printout twice.