Hi
I have a question about the scope of variables for parent and a child
I had written my code here and the output of this but only in child
process the information is completely right even in main the informatin is wrong
well the child process will see the global variable te2 and can change it in its scope
but not the parent nore the main process don't see the changes the child has been made
so what do I have to do ?
thanks for your help and attention
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <wait.h>
struct test
{
int i;
int j;
};
struct test te;
struct test te2;
void test(struct test);
int main()
{
int i=6;
while(i>0)
{
test(te);
i--;
}
printf("\n \n main(): te2.i=%d,te2.j=%d",te2.i,te2.j);
return 0;
}
void test(struct test t)
{
pid_t pid;
int fd[2];
int retval;
if\(pipe\(fd\)<0\)
\{
printf\("\\n pipe error"\);
exit\(0\);
\}
if \(\(pid=fork\(\)\)<0\)
\{
printf\("\\n fork error"\);
exit\(0\);
\}
if \(pid==0\)//child
\{
struct test m;
int retval;
retval=read\(fd[0],&m,sizeof\(m\)\);
if \(retval<0\)
\{
printf\("\\n child error"\);
exit\(0\);
\}
te2.j=7;
printf\("\\n child : t.i=%d, te2.i=%d te2.j=%d",m.i,te2.i,te2.j\);
exit\(EXIT_SUCCESS\);
\}
else
\{
te2.i=8;
t.i=1;
printf\("\\n parent : t.i=%d , te2.i=%d te2.j=%d",t.i,te2.i,te2.j\);
write\(fd[1],&t,sizeof\(t\)\);
getchar\(\);
close\(fd[1]\);
close\(fd[0]\);
\}
}
and the output:
parent : t.i=1 , te2.i=8 te2.j=0
child : t.i=1, te2.i=0 te2.j=7
parent : t.i=1 , te2.i=8 te2.j=0
child : t.i=1, te2.i=8 te2.j=7
parent : t.i=1 , te2.i=8 te2.j=0
child : t.i=1, te2.i=8 te2.j=7
parent : t.i=1 , te2.i=8 te2.j=0
child : t.i=1, te2.i=8 te2.j=7
parent : t.i=1 , te2.i=8 te2.j=0
child : t.i=1, te2.i=8 te2.j=7
parent : t.i=1 , te2.i=8 te2.j=0
child : t.i=1, te2.i=8 te2.j=7
main(): te2.i=8,te2.j=0