Reputation:
Take a look on this code
int main(int argc, char **argv)
{
int pid[3];
int i,tmp;
pid[0]=getpid();
if((tmp=fork()) == 0)
{
pid[2]=getpid();
printf("3. PIDY %d %d %d\n", pid[0], pid[1], pid[2]);
}
else
{
pid[2]=tmp;
if((tmp=fork()) == 0)
{
pid[1]=getpid();
printf("2. PIDY %d %d %d\n", pid[0], pid[1], pid[2]);
}
else
{
pid[1]=tmp;
printf("1. PIDY %d %d %d\n", pid[0], pid[1], pid[2]);
}
}
return 0;
}
On the output im getting smth like that:
1. PIDY 101 102 103
2. PIDY 101 102 103
3. PIDY 101 0 103
Im wondering why im getting pid[1] = 0 in 3rd process? Any idea how to fix it?
Upvotes: 3
Views: 674
Reputation:
i solved problem in this way, much more code but i didnt have any other idea to solve it (i dont have experience with shared memory and pipes) take a look:
FILE * fp;
int pid[3];
void ReadPid()
{ // odczytanie pidow
fp = fopen("/tmp/pid","r");
int r=sizeof(int)*3;
int readed;
char * out = (char*) pid;
while(r>0)
{
readed = fread(out,1,sizeof(pid),fp);
if(readed!= EOF)
{
out+=readed;
r-=readed;
}
}
fclose(fp);
}
int main(int argc, char **argv)
{
int i,tmp;
fp = fopen("/tmp/pid","w");
if(fp==NULL) err("nie mozna otworzyc pliku /tmp/pid");
if((pid[2]=fork())==0)
{
ReadPid();
printf("3. PIDY %d %d %d\n", pid[0], pid[1], pid[2]);
}
else
if((pid[1]=fork())==0)
{
ReadPid();
printf("2. PIDY %d %d %d\n", pid[0], pid[1], pid[2]);
}
else
if((pid[0]=fork())==0)
{
ReadPid();
printf("1. PIDY %d %d %d\n", pid[0], pid[1], pid[2]);
}
else
{
fwrite(pid,1,sizeof(pid),fp);
fclose(fp);
}
return 0;
}
if u got any other idea, please post it
Upvotes: 0
Reputation: 2909
You have to use some sort of signal exchange between the two processes. You may use a pipe or shared memory for complex data or simply signals for simple messages.
Upvotes: 0
Reputation:
The process that prints the 3.
line has already forked off before anything sets pid[1]
. It's not in shared memory, so no values can be stored into it from the other processes, and you never initialized it, so it contains memory dirt, only coincidentally 0.
If the array was declared as a global variable or if it were a static in a function, then the elements would have been initialized to 0
unless already initialized. initial value of int array in C would be a good read.
Upvotes: 5