Sponsored Content
Full Discussion: C fork Confusion :-?
Top Forums Programming C fork Confusion :-? Post 302219638 by ramen_noodle on Tuesday 29th of July 2008 06:07:42 PM
Old 07-29-2008
More a socket programming question in a lot of ways.
Tcp based example, hth.
Fwiw you are right about the child having access to the listening descriptor (via dup()), but you won't be able to accept() on it in the child while in the event loop in the parent, so you could safely close it in the child; in fact that's safe programming.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>
#include <string.h>
#include <sys/wait.h>

#define BSZ 256
#define SRVPORT 81
#define MAXLISTEN 5

void handleconnect(int sck) {
int sz = 0;
char buf[BSZ];

                   if (sck < 0) {perror("socket descriptor invalid"); exit(1);}
                   while ((sz = recv(sck,buf,BSZ,0)) > 0) {
                         printf("\nRead %d bytes at epochtime %d = %s in child: %d\n\n",sz,time(NULL),buf,getpid());
                   }
                   printf("Client disconnected.. %d exiting.\n",getpid());
                   exit(0);
}

int rettcpsrvsock(int portno) {
int fd;
struct sockaddr_in srv;
                      
                       bzero(&srv,sizeof(srv));
                       if ( (fd = socket(AF_INET,SOCK_STREAM,0)) <= 0) {perror("socket()"); return -1;}
                 
                       srv.sin_addr.s_addr = INADDR_ANY;
                       srv.sin_family = AF_INET;
                       srv.sin_port = htons(portno);
                       bind(fd,(struct sockaddr *)&srv,sizeof(srv));
                       listen(fd,MAXLISTEN);
                       return fd;
}

int main(void) {
int sz, csck, lsck;
pid_t foop;
struct sockaddr_in cli;


                          if ( (lsck = rettcpsrvsock(SRVPORT)) < 0) {perror("rettcpsrvsock()"); return 1;}
                          sz =  sizeof(cli);
 
                          while (1) {
                                    if ( (csck = accept(lsck,&cli,&sz)) < 0) {perror("accept()"); return 1;}
                                    if (fork() == 0) {handleconnect(csck);}
                                   /*edit*/ close(csck);
                                    if ( (foop = waitpid(-1,NULL,WNOHANG)) > 0) {printf("Reaped child: %d.\n",foop);}
                          }
return 1; /*not reached*/
}


Last edited by ramen_noodle; 07-29-2008 at 10:07 PM.. Reason: Too quick, descriptor leak.
 

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

confusion with export

Hi, I have written the following two scripts. a.ksh ---> FPATH=/users/kushard autoload b b echo "From a.ksh::" $aa b ---> function b { typeset aa aa="TRUE." echo "From b::" $aa export aa } (1 Reply)
Discussion started by: kdipankar
1 Replies

2. UNIX for Dummies Questions & Answers

unix confusion

:confused: some one please tell me where i can possibly find out what is unix 10.2 and the basic system functions of it is. I really need help! (1 Reply)
Discussion started by: tribb24
1 Replies

3. UNIX for Dummies Questions & Answers

ftp confusion

I'm an intern at a company that recently bought out another business. In doing so, they inherited a unix system that contains files which they need to retrieve. No one in the company, including myself, really understands or knows unix so please respond with the true assumption that I'm a unix... (1 Reply)
Discussion started by: intern
1 Replies

4. UNIX for Dummies Questions & Answers

wc command confusion

Can somebody explain it to me that why wc gives more chars suppose Ab.txt have two lines qwer qasd then wc -c ab.txt will give 10.why not 8.okay may be it is taking count one for each line just in case but why echo "qwer"|wc -C gives 5. Ok with \c it is returning 4. :) (6 Replies)
Discussion started by: Dhruva
6 Replies

5. Shell Programming and Scripting

Sed confusion

Hello all, I am trying to delete all the lines in a particular file having a pattern. The problem is that it has special characters and for some reason is not doing the job. For eg. src_file /home/test/filelist.txt :xxxx:ogog /home/test/RCH/ogogogg /home/test/RYHUJ/HHHH... (3 Replies)
Discussion started by: alfredo123
3 Replies

6. UNIX for Dummies Questions & Answers

'tr' confusion

Good day, everyone! Could anybody explain me the following situation. If I'm running similar script: Var="anna.kurnikova" Var2="Anna Kurn" echo $Var | tr -t "$Var" "$Var2" Why the output is : anna KurniKova instead of Anna Kurnikova? :confused: Thank you in advance for any... (2 Replies)
Discussion started by: Nafanja
2 Replies

7. Cybersecurity

LDAP; confusion

Hello, I hope all is well. Two issues that I am grappling with. One: Is this a true statement: (AIX, LDAP configured), even if authentication is configured with LDAP, the system would still need to be authenticated against local (/etc/passwd); incase of network failure? Two: I can log... (0 Replies)
Discussion started by: rsheikh
0 Replies

8. Shell Programming and Scripting

Confusion with PS

Hello All, I have a problem in counting number of process getting run with my current script name.. Here it is ps -ef | grep $0 | grep -v grep This display just one line with the PID, PPID and other details when i print it in the script. But when I want to count the numbers in my... (11 Replies)
Discussion started by: sathyaonnuix
11 Replies

9. Shell Programming and Scripting

confusion in use of exit 0

hi i am new to shell scripting. i was going thru the part option and arguments. on this section i fail to understand the use of exit 0 in below example . #!/bin/sh USAGE="Usage: $0 " case "$1" in -t) TARGS="-tvf $2" ;; -c) TARGS="-cvf $2.tar $2" ;; *) echo "$USAGE" exit 0 ;; esac... (13 Replies)
Discussion started by: scriptor
13 Replies

10. Shell Programming and Scripting

Confusion in hash

Hi folks, If a declare a direct hash , then the hash element works fine. my %test = ("test",1); print %test; print "\n"; Here in the above, the name of the hash is predeclared... Suppose now I need to create the hash elements dynamically in the for loop. $test="hash"; my... (1 Reply)
Discussion started by: scriptscript
1 Replies
CONTEXT(3PVM)							  PVM Version 3.4						     CONTEXT(3PVM)

NAME
pvm_newcontext - Request new context. pvm_setcontext - Change context. pvm_freecontext - Free existing context. pvm_getcontext - Get current context. SYNOPSIS
C int ctx = pvm_newcontext( void ) int old_ctx = pvm_setcontext( int new_ctx ) int info = pvm_freecontext( ctx ) int ctx = pvm_getcontext( void ) Fortran call pvmfnewcontext( ctx ) call pvmfsetcontext( new_ctx, old_ctx ) call pvmffreecontext( ctx, info ) call pvmfgetcontext( ctx ) PARAMETERS
ctx Context value. new_ctx New context value. old_ctx Prior context value. info Result code. DESCRIPTION
The context functions provide a system-wide unique context and the means to manipulate this context. Contexts provide the ability for communicating tasks to automatically differentiate messages by the context in which they were sent. Thus a message sent in context A by the sender must be received in context A by the recipient. A sender may send in any context. However, a recipient will not accept a message sent in a context that differs from its own. One such use of contexts is with library routines. Using contexts, library routine inter-communication may be logically seperated from the user's application inter-communication. This will prevent the inadvertent receipt of one another's messages. Spawned tasks inherit the spawn-time context of their parent. Existing PVM applications work unchanged using the default context. pvm_newcontext returns a newly allocated context. However, this new context is not yet active. pvm_setcontext changes the current context from old_ctx to new_ctx. pvm_freecontext frees ctx so that it may be reused. Contexts are a system resource that will be exhausted if not recycled. pvm_getcontext returns the current context of the requesting task. EXAMPLES
/* parent task with context */ int cc, context0, context1; char buf[25]; context0 = pvm_getcontext(); /* get my current context */ context1 = pvm_newcontext(); /* get a new context */ pvm_setcontext(context1); /* set my context to new context */ printf("My context is: %d", context1); pvm_spawn("child", (char**)0, PvmTaskDefault, "", 1, &tid); cc = pvm_recv(-1, -1); /* receive message from child - in context1 */ pvm_upkstr(buf); printf("%s", buf); pvm_setcontext(context0); /* reset my context to my original context0 */ /* child task with context - child inherits parent's context as default */ int context; int ptid; char buf[25]; ptid = pvm_parent(); context = pvm_getcontext(); /* get my current context */ sprintf(buf, "Greetings from child who's context is: %d.", context); pvm_initsend(PvmDataDefault); pvm_pkstr(buf); pvm_send(ptid, 1); ERRORS
Only system resource errors will be returned as the context programs themselves do not generate errors. SEE ALSO
8 April, 1997 CONTEXT(3PVM)
All times are GMT -4. The time now is 08:10 PM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy