a simple program to illustrate that child process does not shareresources with parent process

S

sree.harsha.sn

/*here is the program */
#include<stdio.h>
#include<sched.h>
#include<sys/types.h>
#include<fcntl.h>
int main(){
pid_t chpid;
int fd,variable,status;
char ch;
variable=9;
if(fd=open("hello.c",O_RDONLY)==-1) {
printf("unable to open hello.c\n");
return 1;
}

chpid=fork();
if(chpid!=0) {
wait(&status);
}

else {
variable=42;
close(fd);
printf("the child has changed the value of variable to %d
\n",variable);
printf("the child has also closed the file\n");
return 0;
}

printf("the value of variable now is %d\n",variable);

if(read(fd,&ch,1)==-1) {
printf("READ Failed\n");
return 1;
}
else {
printf("Read from file %s",&ch);
}
return 0;
}
/*

*/
the output is as follows

the child has changed the value of variable to 42
the child has also closed the file
the value of variable now is 9

The first three lines are as expected. but after the program goes into
the read function second time it does not come out again Why?
 
C

Chris Dollin

/*here is the program */
#include<stdio.h>
#include<sched.h>
#include<sys/types.h>
#include<fcntl.h>

(fx:snip)

(a) comp.unix.programmer

(b) FIX YOUR LAYOUT.
 
R

Richard Tobin

char ch; ....
if(read(fd,&ch,1)==-1) { ....
printf("Read from file %s",&ch);

The argument for %s needs to be a null-terminated string.
if(fd=open("hello.c",O_RDONLY)==-1) {

== binds more tightly than =. Turning up the warning level on your
compiler would probably have caught this.

-- Richard
 
M

Martien Verbruggen

On Fri, 7 Nov 2008 05:03:10 -0800 (PST),

While almost all of your program is Unix specific, rather than standard
C, your error is a language error:
if(fd=open("hello.c",O_RDONLY)==-1) {

This is the same as

if (fd = (open("hello.c",O_RDONLY) == -1)) {

which is not what you meant. You meant

if ((fd = open("hello.c",O_RDONLY)) == -1) {

Most likely you can get your compiler to warn you about this. If you use
gcc, make sure to include -W and -Wall as command line options.

You also forgot to include some headers that your compiler can warn you
about. If you need mroe help with this program, I suggest you post to
comp.unix.programmer in the future. There are more people there who can
help you with the Unix specific bits.

Martien
 
S

sree.harsha.sn

thanks a lot... i was looking at the second read call in the
program... forgot all about precedences of operators.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top