![]() |
Hello and Welcome from United States to the UNIX and Linux Forums! Thank You for Visiting and Joining Our Global Community.
|
|
google unix.com
|
|||||||
| Forums | Register | Forum Rules | Links | Albums | FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
| High Level Programming Post questions about C, C++, Java, SQL, and other programming languages here. |
More UNIX and Linux Forum Topics You Might Find Helpful
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| File Descriptor | rimser9 | Shell Programming and Scripting | 3 | 08-14-2008 07:34 AM |
| Problems with file descriptor | teo | High Level Programming | 11 | 05-09-2005 12:47 PM |
| File Descriptor Help | rahulrathod | UNIX for Dummies Questions & Answers | 3 | 10-14-2004 06:08 AM |
| file activity (open/closed) file descriptor info using KORN shell scripting | Gary Dunn | UNIX for Dummies Questions & Answers | 3 | 06-07-2004 02:54 PM |
| bad file descriptor? | ftb | UNIX for Dummies Questions & Answers | 1 | 02-20-2002 07:19 PM |
![]() |
|
|
LinkBack | Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
||||
|
share file descriptor between childs
Code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>
#define BUFF_SIZE 256
#define CHILDS 4
#define DATAFILE "Client_Files.txt"
void worker(int n);
char str_buf[BUFF_SIZE];
FILE *datafile_fp;
int i;
char str_buf[BUFF_SIZE];
pid_t id[CHILDS];
int main() {
if((datafile_fp = fopen( DATAFILE, "r"))== NULL)
printf("grimi");
for ( i = 0; i < CHILDS; i++ ){
id[i] = fork();
if( id[i] == 0 ){
worker(i);
exit(0);
}
else if ( id[i] == -1 ){
printf("fork error.\n");
exit(0);
}
else {
//stuff;
}
}
}
void worker(int n) {
fgets(str_buf, BUFF_SIZE, datafile_fp);
printf("%c",str_buf[0]);
}
thanks in advance.. |
|
||||
|
The code you posted has a problem. But even if you solve that problem, there is another one. fork() dup()licates fd's from the parent but if you don't have some kind of synchronous read between the childs, you'll have unexpected results.
Do you really want to use multiple processes to read the same fd? Try running this several times to see what I'm talking about: Code:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define CHILDS_N 5
void worker(int * fd)
{
char buf[20];
memset (buf, 0x0, sizeof (buf));
read(*fd, buf, sizeof (buf)-1);
printf ("%s\n", buf);
}
int
main ()
{
pid_t childs[CHILDS_N];
int fd;
int i;
fd = open ("Client_Files.txt", O_RDONLY);
if (fd == -1)
exit(1);
for (i=0; i < CHILDS_N; i++)
{
childs[i] = fork();
if (childs[i] == 0)
{
worker(&fd);
}
else
{
// printf ("parent: %d\n", getpid());
}
}
}
|
![]() |
| Bookmarks |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|