[LCP]abt IPC

bj at gmx.net bj at gmx.net
Sun Aug 26 19:20:05 UTC 2001


Srinath,

Basically you are creating a child process with fork()
Everything inside "if (childpid == 0) {}" is executed by the childprocess.
The "else {}" is where you put the stuff that you want the parentprocess to
do.
Both processes can run at the same time or you can make the parent wait for
the child 
to finish, etc....
This concept is very basic to unix and is heavily utilized by any program
that has to 
respond to requests from clients. I.e. you can have a http/smtp/whatever
-server bind 
to a specific port. 
Everytime a client initiates a connection the parentprocess "forks" a child
which 
handles the process. The parentprocess is free to wait for further requests
while the 
childs handle the actual task and _exit afterwards.
'man fork' for more

HTH,
/joachim

> #include <stdio.h>
> #include <unistd.h>
> #include <sys/types.h>
> 
> int main(void)
> {
>         int     fd[2], nbytes;
>         pid_t   childpid;
>         char    string[] = "Hello, world!\n";
>         char    readbuffer[80];
> 
>         pipe(fd);
>         
>         if((childpid = fork()) == -1)
>         {
>                 perror("fork");
>                 exit(1);
>         }
> 
>         if(childpid == 0)
>         {
>                 /* Child process closes up input side of pipe */
>                 close(fd[0]);
> 
>                 /* Send "string" through the output side of pipe */
>                 write(fd[1], string, (strlen(string)+1));
>                 exit(0);
>         }
>         else
>         {
>                 /* Parent process closes up output side of pipe */
>                 close(fd[1]);
> 
>                 /* Read in a string from the pipe */
>                 nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
>                 printf("Received string: %s", readbuffer);
>         }
>         
>         return(0);
> }
> 
> i am just learning pipes & IPC.. see the code above
> if fork is successful, childpid is zero and only the code under if 
> should execute.
> in the above if-else loop, the code under if and else both seem to 
> execute. what 
> is the flow here ??
> 
> Thanks
> Srinath
> 

-- 
Joachim Bauernberger
Entwicklung
GMX Aktiengesellschaft
Hanauer Strasse 58, 80993 München
Telefon +49.89.143.39-0
Telefax +49.80.143.39-100
mailto:bj at gmx.net
http://www.gmx.de  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.linux.org.au/pipermail/linuxcprogramming/attachments/20010826/f2cce789/attachment.htm 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/octet-stream
Size: 83 bytes
Desc: not available
Url : http://lists.linux.org.au/pipermail/linuxcprogramming/attachments/20010826/f2cce789/attachment.obj 


More information about the linuxCprogramming mailing list